• 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     void search(vector<vector<int> > &result, vector<int> &tmp, vector<int> &candidates, int index, int target){
     2         int n = candidates.size();
     3         if(index >= n)
     4             return;
     5         while(index+1 < n && candidates[index] == candidates[index+1]){
     6             index++;
     7         }
     8         if(target == 0){
     9             result.push_back(tmp);
    10             return;
    11         }
    12         if(target < candidates[index])
    13             return;
    14         search(result, tmp, candidates, index+1, target);
    15         tmp.push_back(candidates[index]);
    16         search(result, tmp, candidates, index, target-candidates[index]);
    17         tmp.erase(tmp.end()-1);
    18     }
    19     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
    20         // Start typing your C/C++ solution below
    21         // DO NOT write int main() function
    22         vector<vector<int> > result;
    23         vector<int> tmp;
    24         sort(candidates.begin(), candidates.end());
    25         search(result, tmp, candidates, 0, target);
    26         return result;
    27     }
  • 相关阅读:
    Go的几种函数式编程范例
    换零钱和快速幂
    随笔不是博客
    leetcode-51
    leetcode-50
    拨号器
    简易计算器的实现
    python入门:1-100所有数的和
    python入门:输出1-10以内除去7的所有数(简)
    python入门:输出1-10以内除去7的所有数(自写)
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3372999.html
Copyright © 2020-2023  润新知