codekofi
← All questions

Climbing Stairs

Hard1-D Dynamic Programming

The problem

You are climbing a staircase of n steps. Each move you may go up either one step or two steps.

Return the number of distinct ways to reach the top.

For n = 3 the answer is 3: 1+1+1, 1+2, and 2+1.

climbStairs(5)

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1int climbStairs(int n) {
2
3 int prev = 1;
4 int curr = 1;
5
6 for (int i = 1; i < n; i++) {
7 int next = prev + curr;
8 prev = curr;
9 curr = next;
10 }
11
12 return curr;
13}
1int climbStairs(int n) {
2
3 int prev = 1;
4 int curr = 0;
5
6 for (int i = 1; i <= n; i++) {
7 int next = prev + curr;
8 prev = curr;
9 curr = next;
10 }
11
12 return curr;
13}
1int climbStairs(int n) {
2
3 int prev = 1;
4 int curr = 0;
5
6 for (int i = 0; i < n; i++) {
7 int next = prev + curr;
8 prev = curr;
9 curr = next;
10 }
11
12 return curr;
13}