39. Combination Sum I/II
Posted hankunyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了39. Combination Sum I/II相关的知识,希望对你有一定的参考价值。
基础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(); } } };
以上是关于39. Combination Sum I/II的主要内容,如果未能解决你的问题,请参考以下文章