• 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 (a1a2, … , 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] 

    思路

    在上一题基础上增加判断,如果一个数不选择,那么之后所有相同的数字也都不选择。这组题类似subsets那一组。

     1     void search(vector<vector<int> > &result, vector<int> &tmp, vector<int> &candidates, int index, int target){
     2         int n = candidates.size();
     3         if(target == 0){
     4             if(((index < n && (!tmp.empty() && candidates[index] != *(tmp.end()-1)))) || index >= n)
     5                 result.push_back(tmp);
     6             return;
     7         }
     8         if(index >= n)
     9             return;
    10         if(target < candidates[index])
    11             return;
    12         if(tmp.empty() || (!tmp.empty() && *(tmp.end()-1) != candidates[index]))
    13             search(result, tmp, candidates, index+1, target);
    14         tmp.push_back(candidates[index]);
    15         search(result, tmp, candidates, index+1, target-candidates[index]);
    16         tmp.erase(tmp.end()-1);
    17     }
    18     vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
    19         // Start typing your C/C++ solution below
    20         // DO NOT write int main() function
    21         vector<vector<int> > result;
    22         vector<int> tmp;
    23         sort(candidates.begin(), candidates.end());
    24         search(result, tmp, candidates, 0, target);
    25         return result;
    26     }
  • 相关阅读:
    32位和64位的区别
    Git--版本管理的使用及理解
    Maven使用详解
    记录centos7下tomcat部署war包过程
    SSM三大框架整合教程
    Mybatis 框架搭建实例
    Eclipse 出现select type (? = any character,*= any String,Tz=TimeZone)
    JDBC 操作数据库实例
    mysql 常用命令语法
    MySQL下载安装详情教程(Windows)
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3373797.html
Copyright © 2020-2023  润新知