首页 > 代码库 > Combination Sum & Combination Sum II & Combination Sum III
Combination Sum & Combination Sum II & Combination Sum III
方法:采用递归的方式
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> result; sort(candidates.begin(), candidates.end()); vector<int> path; dfs(candidates, 0, target, path, result); return result; } private: void dfs(vector<int> &candidates, int start, int target, vector<int> &path, vector<vector<int>> &result) { if(target == 0) result.push_back(path); else { for(int i=start; i<candidates.size(); ++i) { if(candidates[i] > target) return; path.push_back(candidates[i]); dfs(candidates, i, target-candidates[i], path, result); path.pop_back(); } } } };
Combination Sum II
方法:每次递归中当前数据只访问一次,这里面需要注意一个细节问题:当原始vector中存在重复数字时,最终的结果会出现重复
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> result; vector<int> path; sort(candidates.begin(), candidates.end()); dfs(candidates, target, path, result, 0); sort(result.begin(), result.end()); auto iter = unique(result.begin(), result.end()); result.erase(iter, result.end()); return result; } private: void dfs(vector<int> &candidates, int target, vector<int> &path, vector<vector<int>> &result, int start) { if(target == 0) { result.push_back(path); return; } else { for(int i=start; i<candidates.size(); ++i) { if(candidates[i] > target) return; path.push_back(candidates[i]); dfs(candidates, target-candidates[i], path, result, i+1); path.pop_back(); } } } };
也可以使用一个简单的flag变量
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> result; vector<int> path; sort(candidates.begin(), candidates.end()); dfs(candidates, target, path, result, 0); return result; } private: void dfs(vector<int> &candidates, int target, vector<int> &path, vector<vector<int>> &result, int start) { if(target == 0) { result.push_back(path); return; } else { int prev = -1; for(int i=start; i<candidates.size(); ++i) { if(candidates[i] == prev) continue; if(candidates[i] > target) return; path.push_back(candidates[i]); prev = candidates[i]; dfs(candidates, target-candidates[i], path, result, i+1); path.pop_back(); } } } };
Combination Sum III
方法同上
class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> result; vector<int> path; dfs(k, n, path, result, 1); return result; } private: void dfs(int k, int n, vector<int> &path, vector<vector<int>> &result, int start) { if(path.size() == k && n == 0) result.push_back(path); else { for(int i=start; i<10; ++i) { if(i > n || path.size() > k) return; path.push_back(i); dfs(k, n-i, path, result, i+1); path.pop_back(); } } } };
Combination Sum & Combination Sum II & Combination Sum III
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。