题目:
给定一些数,要求找出相加等于100的所有数。有唯一解。
例:
输入:1,4,57,63,32
输出:1,4,63,32
思路:
从前往后遍历,每个数字有两种对待方法——要或者不要。所以用到递归。先要,之后进行后续递归。如果没有得到结果,就不要这个数字,继续递归。都不行的话就是没有解。
代码:
#include<iostream>
#include<vector>
using namespace std;
bool test(int* v, vector<int>& res, int i, int n, int need){
if(need==0)
return true;
if(need<0)
return false;
if(i>=n)
return false;
//两种情况,要这个数或不要
//要
res.push_back(v[i]);
if(test(v,res,i+1,n,need-v[i])==true)
return true;
//要之后无法满足条件,选择不要
res.pop_back();
if(test(v,res,i+1,n,need)==true)
return true;
//不要也不满足条件
return false;
}
int main()
{
int v[5]={1,4,57,63,32};
vector<int> res;
if(test(v,res,0,5,100)==true){
cout<<"true"<<endl;
for(int i=0;i<res.size();i++)
cout<<res[i]<<endl;
}else{
cout<<"false"<<endl;
}
}