zoukankan      html  css  js  c++  java
  • 【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 (a1a2, … , 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] 

    利用递归搜索,同时剪枝就可以
     
     1 class Solution {
     2 
     3 public:
     4 
     5     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
     6 
     7         
     8 
     9         sort(candidates.begin(),candidates.end());
    10 
    11         vector<vector<int> > result;
    12 
    13         vector<int> tmp;
    14 
    15  
    16 
    17         backtracking(result,candidates,target,tmp,0,0);
    18 
    19         
    20 
    21         return result;
    22 
    23     }
    24 
    25     
    26 
    27     void backtracking(vector<vector<int> > &result,vector<int> &candidates, int &target,vector<int> tmp, int sum,int index)
    28 
    29     {
    30 
    31  
    32 
    33         if(sum==target)
    34 
    35         {
    36 
    37             result.push_back(tmp);
    38 
    39             return;
    40 
    41         }
    42 
    43         else
    44 
    45         {
    46 
    47             int sum0=sum;
    48 
    49             //注意index
    50 
    51             for(int i=index;i<candidates.size();i++)
    52 
    53             {
    54 
    55                 tmp.push_back(candidates[i]);
    56 
    57                 sum=sum0+candidates[i];
    58 
    59                 if(sum>target)
    60 
    61                 {
    62 
    63                     break;
    64 
    65                 }
    66 
    67                 backtracking(result,candidates,target,tmp,sum,i);
    68 
    69                 tmp.pop_back();
    70 
    71             }            
    72 
    73         }        
    74 
    75     }
    76 
    77 };
  • 相关阅读:
    利用 chunked 类型响应实现后台请求的监听
    C/C++ 中的宏/Macro
    SSL/TLS 链接的建立/握手
    C/C++ 中 `printf` 格式化
    多媒体文件的容器与编解码器的关系
    Unix 开发中的 Make 三连
    shell 中长命令的换行处理
    C++ float vs double
    Xcode 中配置 clang-format 格式化 C++ 代码
    C++ `endl` 与 ` ` 的区别
  • 原文地址:https://www.cnblogs.com/reachteam/p/4192428.html
Copyright © 2011-2022 走看看