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

[LeetCode] Combination Sum

时间:2015-05-03 23:45:39      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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 (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] 

解题思路:

这道题的题意是从n个正整数中选出值为特定值的所有元素,这n个数中每个数可以重复选用。

这是一个np难问题,暴力法。主要是通过回溯暴力。代码如下:

class Solution {
public:
    vector<vector<int>> combinationSum(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;  //相当于系数,表示每个数出现了多少次
        getResult(result, candidates, 0, keyToNumber, target);
    }
    
    void getResult(vector<vector<int>>& result, 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(key);
                }
            }
            result.push_back(item);
            return;
        }
        if(candidateIndex>=uniqueCandidates.size()){
            return;
        }
        int number=0;
        while(left>=0){
            if(number!=0)
                keyToNumber[uniqueCandidates[candidateIndex]]=number;
            getResult(result, uniqueCandidates, candidateIndex+1, keyToNumber, left);
            if(number!=0){
                keyToNumber.erase(uniqueCandidates[candidateIndex]);
            }
            left = left-uniqueCandidates[candidateIndex];
            number++;
        }
    }
};


[LeetCode] Combination Sum

标签:c++   leetcode   

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

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