LintCode(M)打劫房屋2——动态规划

506人阅读 评论(0)

i=nums.size()-1;//i为最后一家
a[i]=max(houseRobber(A)+nums[i], houseRobber(B));

A为{nums[1]….nums[i-2]}//少了第一家和最后两家。
2. houseRobber(A)+nums[i]为不抢最后一家的情况，
B为{nums[0]…nums[i-1]}//少了开头第一家。
3.houseRobber是打劫房屋1的代码。

class Solution {
public:
/**
* @param nums: An array of non-negative integers.
* return: The maximum amount of money you can rob tonight
*/
long long houseRobber(vector<int> A) {
// int n = A.size();
vector<long long> a(A.size(), 0);
long long temp1, temp2;
if (A.size() == 1) return A[0];
if (A.size() == 2) return max(A[0], A[1]);
a[0] = 0; a[1] = A[1];

for (int i = 2; i<A.size(); ++i){
a[i] = max(a[i - 2] + A[i], a[i - 1]);
}
temp1 = a[A.size() - 1];
a[0] = A[0]; a[1] = 0;
for (int i = 2; i<A.size(); ++i){
a[i] = max(a[i - 2] + A[i], a[i - 1]);
}
temp2 = a[A.size() - 1];
return max(temp1, temp2);

}

int houseRobber2(vector<int>& nums) {
//for (auto c : nums)cout << c << endl;
if (nums.size() == 1)return nums[0];
if (nums.size() == 2)return 0;
if (nums.size() == 3)return nums[1];
int temp1, temp2;
vector<int>::iterator it = nums.end(), it2,it3;
int b = *(--it);
it2=nums.erase(it);
temp1 = houseRobber(nums);
//for (auto c : nums)cout << c << endl;
//不打劫
//cout << temp1 << endl;
nums.erase(--it2);
it = nums.begin();
nums.erase(it);
//for (auto c : nums)cout << c << endl;
temp2 = houseRobber(nums);
//打劫
//cout << temp2 << endl;
temp2 += b;
int ret = max(temp1, temp2);

//  for (auto c : nums)cout << c<<endl;
return ret;
}

};

class Solution {
public:
/**
* @param nums: An array of non-negative integers.
* return: The maximum amount of money you can rob tonight
*/
long long houseRobber(vector<int> A) {
// int n = A.size();
vector<long long> a(A.size(), 0);
long long temp1, temp2;
if (A.size() == 1) return A[0];
if (A.size() == 2) return max(A[0], A[1]);
/*a[0] = 0; a[1] = A[1];

for (int i = 2; i<A.size(); ++i){
a[i] = max(a[i - 2] + A[i], a[i - 1]);
}
temp1 = a[A.size() - 1];
a[0] = A[0]; a[1] = 0;*/
a[0] = A[0]; a[1] = max(A[0], A[1]);
for (int i = 2; i<A.size(); ++i){
a[i] = max(a[i - 2] + A[i], a[i - 1]);
}
temp2 = a[A.size() - 1];
return temp2;
//return max(temp1, temp2);

}

int houseRobber2(vector<int>& nums) {
//for (auto c : nums)cout << c << endl;
if (nums.size() == 1)return nums[0];
if (nums.size() == 2)return 0;
if (nums.size() == 3)return nums[1];
int temp1, temp2;
vector<int>::iterator it = nums.end(), it2,it3;
int b = *(--it);
it2=nums.erase(it);
temp1 = houseRobber(nums);
//for (auto c : nums)cout << c << endl;
//不打劫
//cout << temp1 << endl;
nums.erase(--it2);
it = nums.begin();
nums.erase(it);
//for (auto c : nums)cout << c << endl;
temp2 = houseRobber(nums);
//打劫
//cout << temp2 << endl;
temp2 += b;
int ret = max(temp1, temp2);

//  for (auto c : nums)cout << c<<endl;
return ret;
}

};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：22054次
• 积分：1561
• 等级：
• 排名：千里之外
• 原创：140篇
• 转载：4篇
• 译文：0篇
• 评论：2条
文章分类
阅读排行
评论排行
最新评论