打劫房屋 II-LintCode
来源:互联网 发布:淘宝上怎么评价不了了 编辑:程序博客网 时间:2024/05/06 13:24
在上次打劫完一条街道之后,窃贼又发现了一个新的可以打劫的地方,但这次所有的房子围成了一个圈,这就意味着第一间房子和最后一间房子是挨着的。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警。
给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,你最多可以得到多少钱 在不触动报警装置的情况下。
注意事项:
这题是House Robber的扩展,只不过是由直线变成了圈
样例:
给出nums = [3,6,4], 返回6,你不能打劫3和4所在的房间,因为它们围成一个圈,是相邻的。
思路:
构建函数,getRes(nums,start,end),返回第start+1间屋子到第end+1间屋子的最大金额。
主要处理头尾两间房屋,当打劫第一间屋子的时候,一定不打劫最后一间屋子,
结果为:getRes(nums,0,len-2)
当不不打劫第一间屋子的时候,从第二间屋子开始,
结果为:getRes(nums,1,len-1)
返回二者最大值。
#ifndef C534_H#define C534_H#include<iostream>#include<vector>using namespace std;class Solution {public: /* * @param nums: An array of non-negative integers. * @return: The maximum amount of money you can rob tonight */ int houseRobber2(vector<int> nums) { // write your code here if (nums.empty()) return 0; int len = nums.size(); if (len == 1) return nums[0]; return maxVal(getRes(nums,0,len-2),getRes(nums,1,len-1)); } int getRes(vector<int> nums, int start, int end) { if (start>end||nums.empty()) return 0; int len = nums.size(); vector<int> dp(len, 0); for (int i = start; i <= end; ++i) { int cnt = i-start + 1; if (cnt == 1) dp[i] = nums[i]; else if (cnt == 2) dp[i] = maxVal(nums[i],nums[i-1]); else { dp[i] = maxVal(dp[i-2]+nums[i],dp[i-1]); } } return dp[end]; } int maxVal(int a, int b) { return a>b ? a : b; }};#endif
阅读全文
0 0
- LintCode:打劫房屋 II
- lintcode --打劫房屋II
- 打劫房屋 II-LintCode
- lintcode(534)打劫房屋 II
- LintCode 打劫房屋 I II III
- MicroSoft/LintCode:M-打劫房屋 II
- LintCode-打劫房屋
- lintcode-打劫房屋
- LintCode-打劫房屋
- Lintcode打劫房屋
- lintcode ----打劫房屋
- lintcode打劫房屋
- 【LintCode】打劫房屋
- lintcode打劫房屋
- LintCode:打劫房屋
- LintCode:打劫房屋 III
- 【LintCode】打劫房屋
- lintcode--打劫房屋
- VS2012中不能新建表的解决办法
- 【codevs 2956】排队问题
- 【bzoj4551】树 并查集
- day6上
- 卷积神经网络
- 打劫房屋 II-LintCode
- MySQL语句
- C语言自定义函数如何返回数组
- PAT Basic 1006
- 2017年ACM青岛站网络赛--A Cubic number and A Cubic Number
- CPP基础知识—关于菱形继承
- CDQ分治和二维偏序
- 奶牛分
- maven package install deploy区别