qiaoxu123
12/26/2018 - 12:59 AM

746. Min Cost Climbing Stairs

//测试性能:Runtime: 12 ms, faster than 26.44%

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n=(int)cost.size();
        vector<int> dp(n);
        dp[0]=cost[0];
        dp[1]=cost[1];
        for (int i=2; i<n; ++i)
            dp[i]=cost[i]+min(dp[i-2],dp[i-1]);
        return min(dp[n-2],dp[n-1]);
    }
};
//测试性能:Runtime: 12 ms, faster than 26.44%

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int b=cost[1],c=cost[0];
        for (int i=2,a; i<cost.size(); ++i,c=b,b=a) a=cost[i]+min(b,c);
        return min(b,c);
    }
};
//测试性能:Runtime: 16 ms, faster than 4.28% 

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        return go(cost, cost.size());
    }
private:
    unordered_map<int,int> memo;
    int go(vector<int>& c, int n){
        if (memo.count(n)) return memo[n];
        if (n<=1) return memo[n]=c[n];
        return memo[n]=(n==c.size() ? 0 : c[n])+min(go(c,n-2),go(c,n-1));
    }
};
//测试性能:Runtime: 4 ms, faster than 100.00%

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int prev1 = 0, prev2 = 0;
        
        for (int i=2; i<=cost.size(); i++)
        {
            int temp = min(cost[i-1] + prev1, cost[i-2] + prev2);
            prev2 = prev1;
            prev1 = temp;
        }
        
        return prev1;
    }
};