[leetcode] 39. Combination Sum

来源:互联网 发布:php mysql 查询 实例 编辑:程序博客网 时间:2024/06/03 21:05

Given a set of candidate numbers (C) 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]]

解法一:

套路是都是需要一个递归函数。另外要考虑的是,为了不出现重复的combination,要先把数字sort一遍,然后用一个idx标示该考虑那些剩下的数字。

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> res;        sort(candidates.begin(), candidates.end());        vector<int> out;        combinationSumDFS(candidates, target, 0, out, res);        return res;    }        void combinationSumDFS(vector<int> &candidates, int target, int idx, vector<int>& out, vector<vector<int>>& res){        if (target < 0) return;        else if (target ==0) res.push_back(out);        else{            for(int i=idx; i<candidates.size(); i++){                out.push_back(candidates[i]);                combinationSumDFS(candidates, target - candidates[i], i, out, res);                out.pop_back();            }        }    }};



0 0