问题:
爬楼梯问题。
给定n阶台阶,一次可以爬一阶or两阶。
求一共有多少种爬楼梯的方法。
Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: n = 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 Constraints: 1 <= n <= 45
解法:DP
- 状态:n阶台阶
- 选择:
- 爬一阶
- 爬两阶
- dp[x]:共有x阶台阶时,可选择爬法个数。
- 状态转移:dp[x] = dp[x-1] + dp[x-2]
- 到达x阶台阶,我们可以由x-1阶+爬一阶,到达
- 也可以由x-2阶+爬两阶,到达。
- 这两种爬法的和即为,到达x阶总共的爬法。
- 状态转移:dp[x] = dp[x-1] + dp[x-2]
- base:
- dp[0]=0
- dp[1]=1
- dp[2]=2:两个一阶 or 一个两阶
代码参考:
1 class Solution { 2 public: 3 //state: 4 // x th stairs. 5 //dp[x] : x stairs, the count of ways to climb 6 //dp[x] = dp[x-1] + dp[x-2] 7 //opt: 8 //case_1: 1 step 9 //case_2: 2 steps 10 //base: dp[0]=0, dp[1]=1, dp[2]=2. 11 int climbStairs(int n) { 12 int dp_1=1, dp_2=2; 13 int res=dp_2; 14 if(n==1) return dp_1; 15 if(n==0) return 0; 16 for(int i=3; i<=n; i++) { 17 res = dp_2+dp_1; 18 dp_1 = dp_2; 19 dp_2 = res; 20 } 21 return res; 22 } 23 };