中级农民
- 积分
- 101
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-9-19
- 最后登录
- 1970-1-1
|
挖坟,贴自己的方法,不过输出的不是偷的房子的坐标,而是房子里的钱的数值。。。【粗心了】。
```c++
#include <iostream>
#include <vector>
#include <memory>
typedef std::vector<int> IntVec;
using namespace std;
class Solution {
public:
vector<int> rob(vector<int>& nums) {
int n = nums.size();
if (n <= 1) { return nums; }
std::pair<int, IntVec> taken(nums[1], { nums[1] });
std::pair<int, IntVec> notTaken(nums[0], { nums[0] });
for (int i = 2; i < n; ++i) {
const auto& val = nums[i];
std::pair<int, IntVec> newNotTaken;
if (taken.first > notTaken.first) {
newNotTaken.first = taken.first;
newNotTaken.second = std::move(taken.second);
} else { // taken.first <= notTaken.first
newNotTaken.first = notTaken.first;
newNotTaken.second = notTaken.second;
}
taken.first = notTaken.first + val;
taken.second = std::move(notTaken.second);
taken.second.push_back(val);
std::swap(newNotTaken, notTaken);
}
if (taken.first > notTaken.first) {
return taken.second;
} else {
return notTaken.second;
}
}
};
int main() {
vector<int> houses = { 5, 8, 2, 3, 10, 12, 7 };
Solution sol;
auto result = sol.rob(houses);
cout << "Robbed Houses: ";
for (auto& c : result) {
cout << c << " ";
}
cout << "\n";
return 0;
}
``` |
|