zoukankan      html  css  js  c++  java
  • [Leetcode] 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] 

    DFS!

     1 class Solution {
     2 public:
     3     void findNext(vector<vector<int> > &res, vector<int> &candidates, vector<int> v, int sum, int target, int idx) {
     4         if (sum > target || idx >= candidates.size()) {
     5             return;
     6         }
     7         if (sum == target) {
     8             res.push_back(v);
     9             return;
    10         }
    11         v.push_back(candidates[idx]);
    12         findNext(res, candidates, v, sum + candidates[idx], target, idx);
    13         v.pop_back();
    14         findNext(res, candidates, v, sum, target, idx + 1);
    15     }
    16     
    17     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
    18         vector<vector<int> > res;
    19         sort(candidates.begin(), candidates.end());
    20         vector<int> v;
    21         findNext(res, candidates, v, 0, target, 0);
    22         return res;
    23     }
    24 };
  • 相关阅读:
    Python并发(一)
    Python协程详解(二)
    Python协程详解(一)
    Python装饰器
    ●BZOJ 3676 [Apio2014]回文串
    ●POJ 3974 Palindrome(Manacher)
    ●BZOJ 1692 [Usaco2007 Dec]队列变换
    ●BZOJ 4698 Sdoi2008 Sandy的卡片
    ●BZOJ 4516 [Sdoi2016]生成魔咒
    ●BZOJ 3238 [Ahoi2013]差异
  • 原文地址:https://www.cnblogs.com/easonliu/p/3641628.html
Copyright © 2011-2022 走看看