zoukankan      html  css  js  c++  java
  • 39. Combination Sum(回溯)

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    The same repeated number may be chosen from candidates unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
      [7],
      [2,2,3]
    ]
    

    Example 2:

    Input: candidates = [2,3,5], target = 8,
    A solution set is:
    [
      [2,2,2,2],
      [2,3,3],
      [3,5]
    ]
    
     1 class Solution {
     2     private List<List<Integer>> res = new ArrayList<>();
     3     public List<List<Integer>> combinationSum(int[] candidates, int target) {
     4         List<Integer> temp = new ArrayList<Integer>();
     5         help(temp,candidates,0,0,target);
     6         return res;
     7     }
     8     private void help(List<Integer> temp,int[] nums,int index,int cursum,int target){
     9         if(cursum>target)
    10             return;
    11         if(cursum==target)
    12             res.add(new ArrayList<Integer>(temp));
    13         for(int i = index;i<nums.length;i++){
    14             temp.add(nums[i]);
    15             help(temp,nums,i,cursum+nums[i],target);
    16             temp.remove(temp.size()-1);
    17         }
    18     }
    19 }

    2019.3.12

     1 class Solution {
     2 public:
     3     vector<vector<int>> finalres ;
     4     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
     5         if(candidates.size()==0) return finalres;
     6         vector<int> curres;
     7         help(0,curres,candidates,0,target);
     8         return finalres;
     9         
    10     }
    11     void help(int cursum,vector<int>& curres,vector<int>& candidates,int index,int target){
    12         if(cursum==target)
    13             finalres.push_back(curres);
    14         if(cursum>target)
    15             return;
    16         for(int i = index;i<candidates.size();i++){
    17             curres.push_back(candidates[i]);
    18             help(cursum,curres,candidates,i,target-candidates[i]);
    19             curres.pop_back();
    20 
    21         }
    22     }
    23 };
  • 相关阅读:
    UVA 1600
    P3366 【模板】最小生成树(堆优化prim)
    P2414 [NOI2011]阿狸的打字机
    P2322 [HNOI2006]最短母串问题
    P4052 [JSOI2007]文本生成器
    P4824 [USACO15FEB]Censoring (Silver) 审查(银)&&P3121 [USACO15FEB]审查(黄金)Censoring (Gold)
    P3966 [TJOI2013]单词
    P2444 [POI2000]病毒
    P3294 [SCOI2016]背单词
    P2922 [USACO08DEC]秘密消息Secret Message
  • 原文地址:https://www.cnblogs.com/zle1992/p/8902391.html
Copyright © 2011-2022 走看看