基础backtracing题,先排序一下,每次传一个参数表示开始的下标。
class Solution { public: vector<vector<int>> res; vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(),candidates.end()); vector<int> tmp; dfs(candidates, target, tmp, 0); return res; } void dfs(vector<int>& candidates, int target, vector<int> &tmp, int start){ if (target<0) return; if (target==0) res.push_back(tmp); for (int i=start;i<candidates.size();++i){ tmp.push_back(candidates[i]); dfs(candidates,target-candidates[i],tmp,i); tmp.pop_back(); } } };
40. Combination Sum II
有重复元素的情况。和Permutation II处理方法类似,如果 i>start && candidates[i] == candidates [i-1] , 说明当前元素是这层dfs的重复元素,不需要再对candidates[i]进行递归了。
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> res; vector<int> cur; sort(candidates.begin(),candidates.end()); dfs(candidates,target,res,cur,0); return res; } void dfs(vector<int>& candidates, int target, vector<vector<int>> &res, vector<int> &cur, int start){ if (target<0) return; if (target==0) res.push_back(cur); for (int i=start;i<candidates.size();++i){ if (i>start && candidates[i]==candidates[i-1]) continue; cur.push_back(candidates[i]); dfs(candidates,target-candidates[i],res,cur,i+1); cur.pop_back(); } } };
原文地址:https://www.cnblogs.com/hankunyan/p/9602329.html
时间: 2024-10-12 13:30:01