标签:
代码如下,注释部分为递归版本,在OJ上运行超时,在本地正常,所以选择迭代版本。
代码如下:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int hasFinal, exceptFinal;
if(nums.size() == 0)
return 0;
if(nums.size() == 1)
return nums[0];
if(nums.size() == 2) {
if(nums[0] > nums[1])
return nums[0];
else
return nums[1];
}
int tmp1, tmp2;
int maxNM1 = max(nums[0], nums[1]);
int maxNM2 = nums[0];
int maxN;
for(int i = 3; i <= nums.size(); i++) {
if(i != 3) {
maxNM2 = maxNM1;
maxNM1 = maxN;
}
tmp1 = maxNM2 + nums[i - 1];
tmp2 = maxNM1;
maxN = max(tmp1, tmp2);
}
return maxN;
//recursive version
/*int hasFinal, exceptFinal;
if(nums.size() == 0)
return 0;
if(nums.size() == 1)
return nums[0];
if(nums.size() == 2) {
if(nums[0] > nums[1])
return nums[0];
else
return nums[1];
}
if(nums.size() == 3) {
hasFinal = nums[0] + nums[2];
if(nums[0] > nums[1])
exceptFinal = nums[0];
else
exceptFinal = nums[1];
if(hasFinal > exceptFinal)
return hasFinal;
else
return exceptFinal;
}
//int hasFinal, exceptFinal;
vector<int> arr1(nums.begin(), nums.end() - 2);
vector<int> arr2(nums.begin(), nums.end() - 1);
hasFinal = rob(arr1) + *(nums.end() - 1);
exceptFinal = rob(arr2);
if(hasFinal > exceptFinal)
return hasFinal;
else
return exceptFinal;*/
}
};
int main() {
vector<int> arr;
arr.push_back(5);arr.push_back(4);arr.push_back(1);arr.push_back(6);
arr.push_back(57);arr.push_back(24);arr.push_back(48);arr.push_back(12);
Solution solution;
cout << solution.rob(arr) << endl;
getchar();
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46779937