39. Combination Sum
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
 - The solution set must not contain duplicate combinations.
 
For example, given candidate set [2, 3, 6, 7] and target 7, 
A solution set is: 
[ [7], [2, 2, 3] ]
Subscribe to see which companies asked this question.
分析
需要使用DFS来做,
[a, b, c, d, e, f, ...]
假设目标为f,数字从小到大排列,那么需要递归到数字f为止。
root(sum:f)           a(sum:f-a)
|                     |
a b c d e choose a => a b c d e 
终止条件:
1 找到结果
2 数组C中,最小的数字比剩余的数字大
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28  | class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> results;        sort(candidates.begin(), candidates.end());        helper(results,vector<int>{},candidates,target,0);        return results;    }    void helper(vector<vector<int>> &results, vector<int> result, vector<int>& c, int target, int index){        for(int i = index; i < c.size(); ++i){            int t = target - c[i];            // if t is little than 0, then also the posibilities next are not necessary to check            if( t < 0){                return;            }            else{                // add c[i] to the result to check all the posibilities                result.push_back(c[i]);                if(t == 0)                    results.push_back(result);                else                    helper(results, result, c, t, i);                // pop c[i] to prepare for checking c[i+1]                result.pop_back();            }//end of else        }//end of for    }//end of helper}; | 
精简版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  | class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> results;        sort(candidates.begin(), candidates.end());        helper(results,vector<int>{},candidates,target,0);        return results;    }    void helper(vector<vector<int>> &results, vector<int> result, vector<int>& c, int target, int index){        if(target == 0){            results.push_back(result);            return;        }        for(int i = index; i < c.size() && target >= c[i]; ++i){            result.push_back(c[i]);            helper(results, result, c, target - c[i], i);            result.pop_back();        }//end of for    }//end of helper}; | 
                    
                
                
            
        
浙公网安备 33010602011771号