LeetCode第 198 题:打家劫舍(C++)

198. 打家劫舍 - 力扣(LeetCode)

注意数组是无序的

当前能偷到的最大收益:max(上次偷到的, 上上次偷到的+现在这家的)

简单的动态规划:

f [ i ] = m a x ( f [ i − 1 ] , f [ i − 2 ] + n u m s [ i ] ) f[i] = max(f[i-1], f[i-2] + nums[i]) f[i]=max(f[i1],f[i2]+nums[i])

class Solution {
public:
    int rob(vector& nums) {
        int bef_pre = 0, pre = 0, cur = 0;//上上次,上次,现在
        for(auto c : nums){
            cur = max(pre, bef_pre+c);
            int tmp = pre;
            pre = cur;
            bef_pre = tmp;
        }
        return cur;
    }
};

换种写法,两个变量就可以:

class Solution {
public:
    int rob(vector& nums) {
        int pre = 0, cur = 0;//上次,现在
        for(auto c : nums){
            int tmp = cur;
            cur = max(cur, pre+c);
            pre = tmp;
        }
        return cur;
    }
};

你可能感兴趣的:(leetcode,leetcode)