leetcode 198打家劫舍

讲解视频见刘宇波leetcode动态规划第三个视频

记忆化搜索代码:

#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
    vector<int>memo;
    int tryRob(int index, vector<int>& nums)
    {
        if (index > nums.size())
        {
            return 0;
        }
        if (memo[index] != -1)
            return memo[index];
        int i;
        int res = 0;
        for (i = index; i < nums.size(); i++)
        {
            res = max(res, nums[i] + tryRob(i + 2, nums));
        }
        memo[index] = res;
        return res;
    }
public:
    int rob(vector<int>& nums) {
        memo = vector<int>(nums.size()+5, -1);
        return tryRob(0,nums);
    }
};

动态规划代码:

#include<bits/stdc++.h>
#include <algorithm>
using namespace std;
class Solution {
    private:
    /*bool cmp(int a, int b)
    {
        return a>b;
    }*/
public:

    int rob(vector<int>& nums) {
        int n = nums.size();
        vector<int>memo(n + 5, 0);
        if (n == 0)
            return 0;
        memo[n] = 0;
        memo[n+1]=0;
        memo[n - 1] = nums[n - 1];
        memo[n-2]=nums[n-2];
        int i;
        int j;
        for (i = n - 3; i >= 0; i--)
        {
            memo[i] = nums[i];
            for(j=i+2;j<n;j++)
            {
                memo[i]=max(memo[i],nums[i]+memo[j]);
            }
            
        }
        sort(memo.begin(),memo.end());
        return memo[memo.size()-1];

    }
};
原文地址:https://www.cnblogs.com/legendcong/p/9355015.html