zoukankan      html  css  js  c++  java
  • 19.2.3 [LeetCode 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 public:
     3     void getsum(vector<vector<int>>&res,vector<int> ans,vector<int>&candidates, int target, int lastidx) {
     4         if (target == 0) {
     5             res.push_back(ans);
     6             return;
     7         }
     8         if (target < candidates[lastidx])return;
     9         for (int i = lastidx; i < candidates.size(); i++) {
    10             if (target < candidates[i])break;
    11             ans.push_back(candidates[i]);
    12             getsum(res, ans, candidates, target - candidates[i], i);
    13             ans.pop_back();
    14         }
    15     }
    16     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    17         sort(candidates.begin(), candidates.end());
    18         vector<vector<int>>res;
    19         vector<int>ans;
    20         getsum(res, ans, candidates, target, 0);
    21         return res;
    22     }
    23 };
    View Code

    感觉可以用dp,不知道会不会快

  • 相关阅读:
    C的联合体和结构体区别
    1_大端模式和小端模式
    1_2017年中兴机试题
    树1---基础
    栈的应用2---后缀表达式
    2 链式存储栈
    2- 栈和队列----之栈
    2) 线性链表
    kaike的FLAGs
    QAQ来自弱鸡的嘲笑
  • 原文地址:https://www.cnblogs.com/yalphait/p/10350697.html
Copyright © 2011-2022 走看看