Problem
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.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
Solution: DP
Time complexity: O(n)
Space complexity: O(n)
C++ O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua // Running time: 0 ms class Solution { public: int climbStairs(int n) { // f[i] = climbStairs(i) vector<int> f(n + 1, 0); f[0] = f[1] = 1; // f[i] = f[i-1] + f[i-2] for (int i = 2;i <= n; ++i) f[i] = f[i - 1] + f[i - 2]; return f[n]; } }; |
C++ O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Running time: 0 ms class Solution { public: int climbStairs(int n) { int two = 1; int one = 1; int curr = 1; // curr = two + one for (int i = 2; i <= n; ++i) { curr = two + one; two = one; one = curr; } return curr; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment