【题解】【DP】【Leetcode】Climbing Stairs
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?
思路:
最简单的DP问题:递归+查表
代码:
1 int climbStairs(int n) { 2 vector<int> memo(n+1, -1);//忘了在memo[0]没有意义的时候,数组初始大小加一。。。 3 return climb(n, memo); 4 } 5 6 int climb(int n, vector<int>& memo){//忘了加&,就会Time Limit Exceeded 7 if(n < 0){ 8 return -1; 9 } 10 else if(n <= 2){ 11 memo[n] = n; 12 return n; 13 } 14 15 if (memo[n-1] == -1) 16 memo[n-1] = climb(n-1, memo);//修改了递归函数名之后没有更改其他函数体中的引用 17 if(memo[n-2] == -1) 18 memo[n-2] = climb(n-2, memo); 19 //return memo[n-1] + 2*memo[n-2];//等等,子问题中好像有重叠 20 return memo[n-1] + memo[n-2]; 21 }