设为首页 加入收藏

TOP

[LeetCode] Combination Sum
2015-11-21 01:03:14 来源: 作者: 【 】 浏览:1
Tags:LeetCode Combination Sum

?

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 (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 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++; } } };
           
          
         
        
       
      
     
    
   
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj2251 Dungeon Master 下一篇CSU1600:Twenty-four point(DFS)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: