直接写了个搜索。
(效率应该不怎么样……)
39. 组合总和
class Solution {
public:
vector<int> temp;
vector<vector<int>> ans;
int tip;
int num[100005];
void solve(int x,int tot){
//if (x>=tip) return;
if (tot==0){
ans.push_back(temp);
return;
}
if (x>=tip) return;
int help=0;
while (help*num[x]<=tot){
//for (int i=1;i<=help;i++){
for (int i=1;i<=help;i++) temp.push_back(num[x]);
solve(x+1,tot-help*num[x]);
for (int i=1;i<=help;i++) temp.erase(temp.end()-1);
//temp.erase(temp.end());
help++;
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
tip=candidates.size();
for (int i=0;i<tip;i++) num[i]=candidates[i];
temp.clear();
ans.clear();
solve(0,target);
return ans;
}
};