o0w0o / ARTS

ARTS 鸽友打卡🐦
2 stars 0 forks source link

leetcode 198 #105

Open hitolz opened 5 years ago

hitolz commented 5 years ago

https://leetcode-cn.com/problems/house-robber/

动态规划的题目。关键是找到状态转移方程。

class Solution {
    public int rob(int[] nums) {
        int length = nums.length;

        if (length == 0) {
            return 0;
        }
        int[] a = new int[length + 1];
        a[0] = 0;
        a[1] = nums[0];
        for (int i = 2; i <= length; i++) {
            a[i] = Math.max(a[i - 2] + nums[i - 1], a[i - 1]);
        }
        return a[length];

    }
}