程式語言 - LeetCode - C++ - 198. House Robber



參考資訊:
https://algo.monster/liteproblems/198
https://www.cnblogs.com/grandyang/p/4383632.html

題目:


解答:

class Solution {
public:
    int rob(vector<int>& nums) {
        int max_step = nums.size();

        vector<int> dp(max_step, -1);

        auto dfs = [&](this auto&& dfs, int step) -> int {
            if (step >= max_step) {
                return 0;
            }

            if (dp[step] != -1) {
                return dp[step];
            }

            dp[step] = max(nums[step] + dfs(step + 2), dfs(step + 1));
            return dp[step];
        };

        return dfs(0);
    }
};