思路:求组合数
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
Given a set of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
*/
void Combination_helper(vector<int>& vec,int begin,int target,int& cur,vector<int>& path)
{
if(begin >=vec.size())
return ;
cur += vec[begin];
path.push_back(vec[begin]);
if(cur == target)
{
for(int i=0;i<path.size();i++)
cout<<path[i]<<endl;
cout<<"=========="<<endl;
}
Combination_helper(vec,begin+1,target,cur,path);
path.pop_back();
cur -= vec[begin];
Combination_helper(vec,begin+1,target,cur,path);
}
void Combination(vector<int>& vec,int target)
{
vector<int> path;
int cur = 0;
if(vec.size() == 0)
return ;
Combination_helper(vec,0,target,cur,path);
}
int main()
{
vector<int> path;
int array[]={2,5,6,7};
int cur =0;
vector<int> vec(array,array+sizeof(array)/sizeof(int));
Combination(vec,7);
return 0;
}
这里需要注意的地方有两点,第一
if(cur == target)
{
for(int i=0;i<path.size();i++)
cout<<path[i]<<endl;
cout<<"=========="<<endl;
}
else
{ Combination_helper(vec,begin+1,target,cur,path);
path.pop_back();
cur -= vec[begin];
Combination_helper(vec,begin+1,target,cur,path);
}不能写成这样,如果有一符合条件,紧接着有一个符合条件 那么不能得以实现。第二个是打印的地方不能return