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

70. Climbing Stairs

2017-11-02 23:42 369 查看
https://leetcode.com/problems/climbing-stairs/description/

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?

Note: Given n will be a positive integer.

解法一:

/*
*dp
= dp[n-1] + dp[n-2]
*就是类似于斐波那契额数列嘛
*/
class Solution {
public:
int climbStairs(int n) {
if(n <= 1)
return 1;
int dp
;
dp[0] = 1;
dp[1] = 2;
for(int i = 2; i < n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n - 1];
}
};


解法二:

对空间进行进一步优化,我们只用两个整型变量a和b来存储过程值。

class Solution {
public:
int climbStairs(int n) {
int a = 1;
int b = 1;
while(--n) {
int tmp = a;
a = a + b;  // 更新dp
= dp[n - 1] + dp[n - 2]
b = tmp;  // 更新dp[n - 1] = dp[n - 2]
}
return a;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: