思路:1 动态规划
用一个三维数组记录从1 到 target的组合。
1 每个数可能出现1 到 target次。遍历从1 到 t 的所有目标
2 遍历数组中小于目标 t 的数,
3 对于每个候选“c”,我们运行目标t-c的所有组合,从大于或等于c的值开始,以避免重复并仅存储有序组合。
思路2 回溯法
代码:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
/*
vector<vector<int>> res;
vector<int> path;
sort(candidates.begin(),candidates.end());
backPath(candidates,res,path,target,0);
return res;*/
vector<vector<int>> result;
int size = candidates.size();
if (size == 0) return result;
sort(candidates.begin(), candidates.end());
vector<vector<vector<int>>> dp(target + 1, vector<vector<int>>());
dp[0].push_back(vector<int>());
for (int i = 1; i <= target; ++i) {
for (int j = 0; j < size && candidates[j] <= i; ++j) {
for (int k = 0; k < dp[i - candidates[j]].size(); ++k) {
vector<int> temp = dp[i - candidates[j]][k];
if (temp.size() && (temp[temp.size() - 1] > candidates[j])) continue;
temp.push_back(candidates[j]);
dp[i].push_back(temp);
}
}
}
return dp[target];
}
/*
void backPath(vector<int>& candidates,vector<vector<int>>& res,vector<int>& path,int target,int start){
if(target == 0){
res.push_back(path);
return;
}
for(int i = start; i < candidates.size(); i++){
if(target < candidates[i])
return ;
path.push_back(candidates[i]);
backPath(candidates,res,path,target - candidates[i],i);
path.pop_back();
}
}*/