本文共 845 字,大约阅读时间需要 2 分钟。
方法一:递归法(超出时间限制)class Solution { private: int recursive(int n){ if(n==0||n==1) return 1; return recursive(n-1)+recursive(n-2); }public: int climbStairs(int n) { return recursive(n); }};
方法二:记忆化搜索
class Solution { private: vector memo; int recursive(int n){ if(n==0||n==1) return 1; if(memo[n] == -1) memo[n] = recursive(n-1)+recursive(n-2); return memo[n]; }public: int climbStairs(int n) { memo = vector (n+1,-1); return recursive(n); }};
方法三:动态规划
class Solution { public: int climbStairs(int n) { vector memo(n+1,-1); memo[0] = memo[1] = 1; for(int i=2;i<=n;i++) memo[i] = memo[i-1]+memo[i-2]; return memo[n]; }};
转载地址:http://dvyci.baihongyu.com/