Sunday, August 2, 2015

040 - Combination Sum II

Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Hide Tags
Array Backtracking
Hide Similar Problems
(M) Combination Sum

039的基础上加了要求:
每个数字只能用一次(但是如果集合里有两个x,一条结果里还是可以同时有两个x,每个x各用一次嘛)。
所以加了黄色的部分,每次从下一个元素开始。
但是这样还可能造成另一个问题,就是duplicated的结果,
循环下一轮用的下一个元素,可能跟当前的相对,以下一元素来组合的结果就可能跟上一个组合出来的一样了。
要避免这一现象,就可以在递归调用之后,跨过同样的元素,从新的起点开始。(类似在090 - Subsets II里的处理)

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> rst;
        vector<int> buf;
        int sz=candidates.size();
        if(sz)
        {
            sort(candidates.begin(), candidates.end());

            for(int ii=0; ii<sz; ++ii)
            {
                buf.push_back(candidates[ii]);
                getPromisingNum(candidates, sz, ii+1, target-candidates[ii], buf, rst);
                buf.pop_back();
                while((ii<sz-1)&&(candidates[ii]==candidates[ii+1]))

                    ii++;
            }
        }
        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+1, tgt-candidates[ii], buf, rst);
                    buf.pop_back();
                    while((ii<sz-1)&&(candidates[ii]==candidates[ii+1]))
                        ii++;
                }
        }
        return;
    }
};

8 ms.

No comments:

Post a Comment