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.
解法一:
解法二:
对空间进行进一步优化,我们只用两个整型变量a和b来存储过程值。
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; } };
相关文章推荐
- 70. Climbing Stairs
- 70. Climbing Stairs
- 70. Climbing Stairs
- [LeetCode]problem 70. Climbing Stairs
- 70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- 70. Climbing Stairs
- Leetcode刷题记——70. Climbing Stairs(爬楼梯)
- 70. Climbing Stairs dynamic programming
- 70. Climbing Stairs
- 70. Climbing Stairs
- 70. Climbing Stairs
- 70. Climbing Stairs
- leetcode 70. Climbing Stairs
- 70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- 70. Climbing Stairs
- 70. Climbing Stairs#1(Done)
- Leet Code OJ 70. Climbing Stairs(爬楼梯问题)