• [LeetCode]Combination Sum II


    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] 

    dfs,深搜遍历,set去重,很好理解。

     1 class Solution {
     2 public:
     3     void dfs(vector<int> candidates,int target,int start,vector<int> tmp,set<vector<int>>& result_set)
     4     {
     5         int sum=0;
     6         for(int i=0;i<tmp.size();i++)
     7         {
     8             sum+=tmp[i];
     9         }
    10         if(sum==target)
    11         {
    12             sort(tmp.begin(),tmp.end());
    13             result_set.insert(tmp);
    14             return;
    15         }
    16         else if(sum>target)
    17         {
    18             return;
    19         }
    20         for(int i=start;i<candidates.size();i++)
    21         {
    22             tmp.push_back(candidates[i]);
    23             dfs(candidates,target,i+1,tmp,result_set);
    24             tmp.pop_back();
    25         }
    26     }
    27     vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
    28         vector<int> tmp;
    29         set<vector<int>> result_set;
    30         vector<vector<int>> result;
    31         dfs(candidates,target,0,tmp,result_set);
    32         set<vector<int>>::iterator it;
    33         for(it=result_set.begin();it!=result_set.end();it++)
    34         {
    35             result.push_back(*it);
    36         }
    37         return result;
    38     }
    39 };
  • 相关阅读:
    Linux基础知识
    oracle用户及表空间基础
    渗透测试之目录扫描-Dirbuster
    oracle自定义函数身份证15位和18位的转换
    linux 网络带宽和延时测试
    LNMP(linux+nginx+mysql+php)服务器环境配置
    使用Medusa美杜莎暴力破解SSH密码
    暴力密码在线破解工具
    在linux下搭建NFS服务器实现文件共享
    Nginx是做什么的
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4815498.html
Copyright © 2020-2023  润新知