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:
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++; } } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45462481