1. 程式人生 > >39. Combination Sum I/II

39. Combination Sum I/II

開始 sta targe date trac rac () size 處理方法

基礎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