2017.12.18 LeetCode

来源:互联网 发布:淘宝客算销量吗 编辑:程序博客网 时间:2024/05/29 04:17

198. House Robber

Description

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

题意: 给你一个连串数据,表示一些店,你要尽可能的抢东西,使得抢的和最大,但是,你不能连续抢连续两家店

分析: 这是一道dp的入门题,可以从上到底深搜一遍,也可以自底向上递推过来,很容易想,考虑某家店时,只有两种状态,抢和不抢,如果抢的话,导致下一家店不可以抢,如果不抢的话,下一家店就可以抢,考虑这是深搜,记忆化下,不然TLE

dfs参考函数

class Solution {public:    int vis[10000];    int dfs(vector<int>& nums,int idx) {        if(idx < 0) return 0;        if(vis[idx] >= 0) return vis[idx];        vis[idx] = max(dfs(nums,idx - 2) + nums[idx],dfs(nums,idx - 1));        return vis[idx];    }    int rob(vector<int>& nums) {        for(int i = 0;i < nums.size();i++) {            vis[i] = -1;        }        return dfs(nums,nums.size()-1);    }};

递推参考函数

class Solution {public:    int vis[10000];    int rob(vector<int>& nums) {        if(nums.size() == 0) return 0;        for(int i = 0;i < nums.size();i++) {            vis[i] = -1;        }        vis[0] = nums[0];        vis[1] = max(nums[0],nums[1]);        for(int i = 2;i < nums.size();i++) {            vis[i] = max(vis[i - 2] + nums[i],vis[i - 1]);        }        return vis[nums.size()-1];    }};
原创粉丝点击