zoukankan      html  css  js  c++  java
  • Leetcode 39. Combination Sum

    39. Combination Sum

    • Total Accepted: 102477
    • Total Submissions: 316416
    • Difficulty: Medium

    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.
    • 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]
    ]

    思路:回溯法遍历元素,满足条件就返回。

    代码:

     1 class Solution {
     2 public:
     3     vector<vector<int>> res;
     4     void combinationSum(vector<int>& v,vector<int>& candidates,int target,int cur){
     5         if(target==0){
     6             res.push_back(v);
     7             return;
     8         }
     9         int i,n=candidates.size();
    10         for(i=cur;i<n;i++){
    11             target-=candidates[i];
    12             if(target>=0){
    13                 v.push_back(candidates[i]);
    14                 combinationSum(v,candidates,target,i);
    15                 v.pop_back();
    16             }
    17             else{//剪枝
    18                 return;
    19             }
    20             target+=candidates[i];
    21         }
    22     }
    23     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    24         sort(candidates.begin(),candidates.end());
    25         vector<int> v;
    26         combinationSum(v,candidates,target,0);
    27         return res;
    28     }
    29 };
  • 相关阅读:
    Codeforces Round #313 (Div. 2) D. Equivalent Strings 解题心得
    UVA
    2015 HUAS Summer Contest#1~A
    2015 HUAS Summer Training#2~D
    2015 HUAS Summer Training#2~C
    2015 HUAS Summer Training#2~E
    2015 HUAS Summer Training#2~A
    2015 HUAS Provincial Select Contest #1
    2015 HUAS Provincial Select Contest #1~F
    2015 HUAS Provincial Select Contest #2~A
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5711140.html
Copyright © 2011-2022 走看看