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> combinationSum(vector & candidates, int target) { vector > result; int len=candidates.size(); if(len==0){ return result; } std:sort(candidates.begin(), candidates.end()); map keyToNumber; //相當於系數,表示每個數出現了多少次 getResult(result, candidates, 0, keyToNumber, target); } void getResult(vector >& result, vector & uniqueCandidates, int candidateIndex, map & keyToNumber, int left){ if(left<0){ return; } if(left==0){ vector item; for(map ::iterator it=keyToNumber.begin(); it!=keyToNumber.end(); it++){ int number=it->second; int key = it->first; for(int i=0; i =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++; } } };