您的位置:首页 > 大数据 > 人工智能

Leetcode: Climbing Stairs

2014-10-04 02:11 239 查看
You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

The following solution uses the equation step[ i ] = step[i - 1] + step[i - 2], but require O(n) space.

public class Solution {
public int climbStairs(int n) {
int[] step = new int[n + 1];
step[0] = 1;
step[1] = 1;
for (int i = 2; i <= n; i++) {
step[i] = step[i - 1] + step[i - 2];
}
return step
;
}
}
Since we don't need the results of previous steps, there's no need to use an array. Only need to store the last result. So revise the above code to the following:

public class Solution {
public int climbStairs(int n) {
int last = 1;
int lastlast = 1;
int res = 1;
for (int i = 2; i <= n; i++) {
res = last + lastlast;
lastlast = last;
last = res;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode