zoukankan      html  css  js  c++  java
  • 19.2.3 [LeetCode 40] Combination Sum II

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    Each number in candidates may only be used once in the combination.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    

    Example 2:

    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]
     1 class Solution {
     2 public:
     3     void getsum(set<vector<int>>&res,vector<int> ans,vector<int>&candidates, int target, int lastidx) {
     4         if (target == 0) {
     5             res.insert(ans);
     6             return;
     7         }
     8         if (target < candidates[lastidx])return;
     9         for (int i = lastidx+1; 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>> combinationSum2(vector<int>& candidates, int target) {
    17         sort(candidates.begin(), candidates.end());
    18         set<vector<int>>res;
    19         vector<int>ans;
    20         getsum(res, ans, candidates, target, -1);
    21         return vector<vector<int>>(res.begin(),res.end());
    22     }
    23 };
    View Code

    上一题稍微改了一下

  • 相关阅读:
    2个准则,解决人际、团队和客户问题
    系统思维
    如何看透他人行为背后的本质 | 思维模型02:行为分析模型
    提问比回答更有力量
    有了套路,为什么还是解决不了问题
    能够跨界成功的人
    正确的思考
    你的烦恼,全因为不会思考
    努力,到底是不是天赋
    我们是魔术师面前的观众吗
  • 原文地址:https://www.cnblogs.com/yalphait/p/10351182.html
Copyright © 2011-2022 走看看