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, a1 ≤ a2 ≤ … ≤ 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] 

class Solution {
public:
    int _sum(vector<int> tmp) {
        int sum = 0;
        int i;
        for (i=0; i<tmp.size(); i++){
            sum+= tmp[i];
        }
        return sum;
    }
    /*
     * 和前面的不同是:
     * 1.每个数字是有限制的
     * 2.注意start下标不一定是从下个相邻的数开始的,是从下个不同的数开始的
     */
    void combination(vector<int>& candidates, vector<vector<int>> &res, vector<int> tmp, int target, int start) {
        //计算选择集的和
        int sum = _sum(tmp);
        if (start >= candidates.size() || sum > target || sum + candidates[start] > target) {
            return;
        }
        //得到当前数出现的次数和下个不同数的下标
        int index = start;
        int num = candidates[start];
        int num_times = 0;
        while (num == candidates[start]) {
            num_times++;
            start++;
        }

        int i = 0;
        while (i < num_times) {
            i++;
            sum += candidates[index];
            tmp.push_back(candidates[index]);
            index++;
            //如果选择集的和小于target
            if (sum < target) {
                if (start < candidates.size()) {
                    combination(candidates, res, tmp, target, start);
                }
            //等于target时,将当前集加入结果集    
            } else if (sum == target) {
                res.push_back(tmp);
                break;
            //如果大于,就不循环了    
            } else {
                break;
            }
        }
        //将选择集中和当前数相等的数目全部删除
        while (i--) {
            tmp.pop_back();
        }
        //当前数都不存在时,计算
        if (start < candidates.size()) {
            combination(candidates, res, tmp, target, start);
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<int> tmp = {};
        int start = 0;
        vector<vector<int>> res;
        sort(candidates.begin(), candidates.end());
        combination(candidates, res, tmp, target, start);
        return res;
    }
};

 

posted on 2016-02-07 15:03  walkwalkwalk  阅读(147)  评论(0编辑  收藏  举报

导航