码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Combination Sum II

时间:2015-05-04 15:33:51      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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 (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 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

解题思路:

与combination sum类似,与之不同的是,每个候选元素只能用一次。

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> result;
        int len=candidates.size();
        if(len==0){
            return result;
        }
        std:sort(candidates.begin(), candidates.end());
        map<int, int> keyToNumber;  //相当于系数,表示每个数出现了多少次,注意,这里变成下标,而非数了。
        set<vector<int>> contains;  //是否包含了这组解
        getResult(result, contains, candidates, 0, keyToNumber, target);
    }
    
    void getResult(vector<vector<int>>& result, set<vector<int>>& contains, vector<int>& uniqueCandidates, int candidateIndex, map<int, int>& keyToNumber, int left){
        if(left<0){
            return;
        }
        if(left==0){
            vector<int> item;
            for(map<int, int>::iterator it=keyToNumber.begin(); it!=keyToNumber.end(); it++){
                int number=it->second;
                int key = it->first;
                for(int i=0; i<number; i++){
                    item.push_back(uniqueCandidates[key]);
                }
            }
            if(contains.find(item)==contains.end()){
                result.push_back(item);
                contains.insert(item);
            }
            return;
        }
        if(candidateIndex>=uniqueCandidates.size()){
            return;
        }
        int number=0;
        while(left>=0&&number<2){   //用0次或一次
            if(number!=0)
                keyToNumber[candidateIndex]=number;
            getResult(result, contains, uniqueCandidates, candidateIndex+1, keyToNumber, left);
            if(number!=0){
                keyToNumber.erase(candidateIndex);
            }
            left = left-uniqueCandidates[candidateIndex];
            number++;
        }
    }
};


[LeetCode] Combination Sum II

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45480979

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!