day48 动规.p9

- 198.打家劫舍 
```cpp
class Solution {

public:

    int rob(vector& nums) {

        if (nums.size() == 1) return nums[0];

        vector dp(nums.size(), 0);

        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], dp[i - 2] + nums[i]);

        }

        return dp[nums.size() - 1];

    }

};
```
- 213.打家劫舍II  
```cpp
class Solution {

public:

    int robRange(vector& nums, int start, int end) {

        if (start == end) return nums[start];

        vector dp(nums.size(), 0);

        dp[start] = nums[start];

        dp[start + 1] = max(nums[start], nums[start + 1]);

        for (int i = start + 2; i <= end; i++) {

            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);

        }

        return dp[end];

    }

    int rob(vector& nums) {

        if (nums.size() == 1) return nums[0];

        int result1 = robRange(nums, 0, nums.size() - 2);

        int result2 = robRange(nums, 1, nums.size() - 1);

        return max(result1, result2);

    }

};
```
- 337.打家劫舍III
```cpp
class Solution {

public:

    // 0偷 1不偷

    vector robTree(TreeNode* cur) {

        if (!cur) return {0, 0};

        vector left = robTree(cur->left);

        vector right = robTree(cur->right);

        // 偷cur

        int val1 = cur->val + left[1] + right[1];

        // 不偷cur

        int val2 = max(left[0], left[1]) + max(right[0], right[1]);

        return {val1, val2};

    }

    int rob(TreeNode* root) {

        vector result = robTree(root);

        return max(result[0], result[1]);

    }

};
```

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