zoukankan      html  css  js  c++  java
  • Combination-Sum II

    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.
    Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
    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]

     1 class Solution {
     2 public:
     3     vector<vector<int> > combinationSum2(vector<int> &num, int target) {
     4         sort(num.begin(), num.end());
     5         vector<vector<int> > res;
     6         vector<int> com;
     7         combinationSum2(num, target, res, com, 0);
     8         return res;
     9     }
    10     
    11     void combinationSum2(vector<int>& num, int target, vector<vector<int> > &res, vector<int> &com, int start)
    12     {
    13         if(target == 0) {
    14             res.push_back(com);
    15             return;
    16         }
    17         for(int i = start; i < num.size() && num[i] <= target; i++) {
    18             if(i > start && num[i] == num[i-1]) continue;  // !duplicate cases
    19             com.push_back(num[i]);
    20             combinationSum2(num, target-num[i], res, com, i+1);
    21             com.pop_back();
    22         }
    23     }
    24 };
  • 相关阅读:
    JUnit4.13环境配置
    OO第5-7次作业总结
    电梯的一点浅优化
    C++变量作用域、生存期、存储类别
    最后一次OO博客
    OO第三次总结
    OO第二次总结
    OO第一次总结
    POJ3934
    POJ刷题计划
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646360.html
Copyright © 2011-2022 走看看