题意:n个数,找出所有不同组合,使组合的和为t。
code:
class Solution {
vector<int> re;
int *id;
vector<vector<int> > ans;
int n;
int tar;
void dfs(int s,int k,int i){
if (k>=n)return;
if (s>tar) return;
id[i] = k;
if (s==tar){
vector<int> t;
REP(j,0,i+1){
t.push_back(re[id[j]]);
}
ans.push_back(t);
return;
}
REP(a,k+1,n){
dfs(s+re[a],a,i+1);
while (a<(n-1)&&re[a+1]==re[a]) a++;
}
}
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(),num.end());
re = num;
n = num.size();
tar = target;
id = new int[num.size()+10];
REP(i,0,n){
dfs(re[i],i,0);
while((i<(n-1))&&re[i+1]==re[i]){
i++;
}
}
return ans;
}
};