测试程序,觉得蛮对的。没有想明白错在哪里。。。
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int recursion(vector<int> vec){
if(vec.empty())
return 0;
//如果按照上面的写法,之后上面所有的都会被覆盖
if(vec.size() == 1)
return vec[0];
sort(vec.begin(),vec.end());
vector<int> ret;
int i = vec.size()-2;
for(;i >= 0;i -= 2){
int h = vec[i+1] - vec[i];
if(h)
ret.push_back(h);
}
if(i == -1 && vec[0]){
ret.push_back(vec[0]);
}
int res = recursion(ret);
return res;
//recursion(ret);
//return 0;
//这样写的话,除了最上一层返回的是vec[0],之外都被其他层的0覆盖掉
}
int main(void){
// vector<int> stone = {2,7,4,1,8,1};
// vector<int> stone = {1,1,1,1};
vector<int> stone = {316,157,73,106,771,
828,46,212,926,604,600,992,71,51,477,869,
425,405,859,924,45,187,283,590,303,66,508,
982,464,398};//{3,7,2};
cout << recursion(stone) << endl;
return 0;
}
参考别人的程序
int lastStoneWeight(vector<int>& stones) {
if (stones.size() == 1) return stones[0];
priority_queue<int> res;
//优先队列大顶堆
int s1, s2;
for (auto& s : stones)
res.push(s);
while (res.size() > 1) {
s1 = res.top();
res.pop();
s2 = res.top();
res.pop();
if (s1 != s2) res.push(s1 - s2);//s1>=s2 所以这里是不需要用abs函数的
}
return res.empty() ? 0 : res.top();
}