• 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,不知道会不会快

  • 相关阅读:
    IPC机制 用Messenger进行进程间通信
    Android 远程Service
    创建前台 Service
    可见性和可达性,C#和C++
    set,map存储问题
    const形参和非const形参
    数组const形参和非const形参的区别
    switch 变量定义报错
    修改oracle用户密码永不过期
    面向对象语言成员变量方法可见性在继承中的变化
  • 原文地址:https://www.cnblogs.com/yalphait/p/10350697.html
Copyright © 2020-2023  润新知