LeetCode(39)-Combination Sum

来源:互联网 发布:g3开票软件 编辑:程序博客网 时间:2024/06/11 21:19

问题描述:

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

问题分析:

先排好序,然后用DFS,有两种选择,一选择当前数然后递归当前数,二不选择当前数直接递归下一个数

问题求解一:

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> ret;        vector<int> temp;        int n = candidates.size();        if (n == 0)            return ret;        sort(candidates.begin(), candidates.end());        dfs(candidates, target, 0, temp, ret);        return ret;    }private:    void dfs(vector<int>& candidates, int target, int start, vector<int> temp, vector<vector<int>> &ret)     {        int n = candidates.size(), i = 0;        if (target < candidates[start])            return;        for (i = start; i < n; i++)        {            temp.push_back(candidates[i]);            if (target == candidates[i])            {                ret.push_back(temp);                return;            }            else if (target > candidates[i])            {                dfs(candidates, target-candidates[i], i, temp, ret);            }            else                return;            temp.pop_back();        }    }};

问题求解二:

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> ans;        vector<int> single;        sort(candidates.begin(), candidates.end());        dfs(ans, single, candidates, 0, target);        return ans;    }private:    void dfs( vector<vector<int>> &ans, vector<int>& single, vector<int>& candi, int cur, int rest)     {        int sz = candi.size();        if( sz <= cur || rest < 0) return;        if( rest == 0){            ans.push_back(single);            return;        }                single.push_back(candi[cur]);        dfs(ans, single, candi, cur, rest-candi[cur]);        single.pop_back();        dfs( ans, single, candi, cur + 1, rest);    }};


0 0
原创粉丝点击