• 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     }
  • 相关阅读:
    Spring MVC异常处理
    tomcat bio nio apr 模式性能测试
    事务中处理异常
    Cookie和Session
    SpringMVC表单标签简介
    <mvc:annotation-driven/>
    真机调试
    Xcode 9,真机测试,App installation failed
    KONE-FLOW Vistor Key
    cordova 内部API 用ssl https,报错
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3373797.html
Copyright © 2020-2023  润新知