zoukankan      html  css  js  c++  java
  • Leetcode 40. Combination Sum II

    40. Combination Sum II

    • Total Accepted: 76278
    • Total Submissions: 265535
    • Difficulty: Medium

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

    Each number in C 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.

    For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
    A solution set is: 

    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]

    思路:还是用回溯法找解,和Leetcode 39. Combination Sum类似。但要注意重复元素造成的干扰,本题排序后,如果有candidates[i]==candidates[i+1]==...==candidates[i+k],只要对candidates[i]进行回溯求解就可以,剩下的candidates[i+1]...candidates[i+k]直接跳过,所以本层的下一个遍历从candidates[i+k+1]开始。

    代码:

     1 class Solution {
     2 public:
     3     vector<vector<int> > res;
     4     void combinationSum2(vector<int>& v,vector<int>& candidates,int target,int cur){
     5         if(!target){
     6             res.push_back(v);
     7             return;
     8         }
     9         int n=candidates.size(),i;
    10         for(i=cur;i<n;i++){
    11             target-=candidates[i];
    12             if(target>=0){
    13                 v.push_back(candidates[i]);
    14                 combinationSum2(v,candidates,target,i+1);
    15                 v.pop_back();
    16             }
    17             else{
    18                 return;
    19             }
    20             target+=candidates[i];
    21             while(i+1<n&&candidates[i]==candidates[i+1]) i++;//去除重复元素导致的重复场景
    22         }
    23     }
    24     vector<vector<int> > combinationSum2(vector<int>& candidates, int target) {
    25         sort(candidates.begin(),candidates.end());
    26         vector<int> v;
    27         combinationSum2(v,candidates,target,0);
    28         return res;
    29     }
    30 };
  • 相关阅读:
    P4213【模板】杜教筛
    【SDOI2006】线性方程组
    【AHOI2018】排列
    【NOI2001】炮兵阵地
    【NOIP2012】疫情控制
    【AHKOI2017】rexp
    【十二省联考2019】春节十二响
    【TJOI2014】匹配
    【AT2645】Exhausted?
    P3809 【模板】后缀排序
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5711887.html
Copyright © 2011-2022 走看看