198-打家劫舍(动态规划)

198-打家劫舍(动态规划)_第1张图片

class Solution {
public:
    int rob(vector<int>& nums) {
        int length = nums.size();
        if (length <= 1) {
            if (length == 0) {
                return 0;
            }
            else {
                return nums[0];
            }
        }
        int *dp = new int[length];
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        for (int i = 2; i < nums.size(); i++) {
            dp[i] = max(dp[i - 1], nums[i] + dp[i - 2]);
        }
        return dp[length - 1];
    }
};

你可能感兴趣的:(腾讯精选50)