Sunday, August 2, 2015

039 - Combination Sum

Combination Sum

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 (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ 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]
Hide Tags
Array Backtracking
Hide Similar Problems
(M) Letter Combinations of a Phone Number (M) Combination Sum II (M) Combinations (M) Combination Sum III

组合吧,数字!
包含重复的就是递归进去的时候仍然从当前数字开始。
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> rst;
        vector<int> buf;
        int sz=candidates.size();
        if(sz)
        {
            sort(candidates.begin(), candidates.end());
           
            int tgt = target;
            for(int ii=0; ii<sz; ++ii)
            {
                buf.push_back(candidates[ii]);
                getPromisingNum(candidates, sz, ii, tgt-candidates[ii], buf, rst);
                buf.pop_back();
            }
        }
        return rst;
    }
   
    void getPromisingNum(vector<int>& candidates, int sz, int start,

                            int tgt, vector<int>& buf, vector<vector<int>>& rst)
    {
        if(!tgt)
            rst.push_back(buf);
        else
        {
            if(tgt>=candidates[start])

                for(int ii=start; ii<sz; ++ii)
                {
                    buf.push_back(candidates[ii]);
                    getPromisingNum(candidates, sz, ii, tgt-candidates[ii], buf, rst);
                    buf.pop_back();
                }
        }
        return;
    }
};

16 ms.

No comments:

Post a Comment