dp的做法:
错误解法一:
n=1的时候,申请的vector只有2个大小,dp[2]=2就错误了
class Solution { public: int climbStairs(int n) { vector<int> dp(n+1); dp[1] = 1; dp[2] = 2; if(n == 1 || n== 2) return dp[n]; for(int i = 3;i <= n;i++) dp[i] = dp[i-1] + dp[i-2]; return dp[n]; } };
正解:
class Solution { public: int climbStairs(int n) { if(n == 1 || n == 2) return n; vector<int> dp(n+1); dp[1] = 1; dp[2] = 2; for(int i = 3;i <= n;i++) dp[i] = dp[i-1] + dp[i-2]; return dp[n]; } };
dp的做法要申请空间,会有空间消耗。可以设计参数的方式来实现:
class Solution { public: int climbStairs(int n) { int num1 = 1; int num2 = 2; int num3; if(n == 1) return 1; if(n == 2) return 2; for(int i = 3;i <= n;i++){ num3 = num1 + num2; num1 = num2; num2 = num3; } return num3; } };