zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    VS中常用设置记录
    MSBUILD结合批处理编译
    Linq to XML 基本类
    在Winform和WPF中注册全局快捷键
    Unity 配置文件 基本设置
    C# 通用Clone
    三次样条插值特点与实现 (引用了一点别人代码,但做了改动!)
    修正短时自相关函数
    矩阵的基本运算
    去红眼不完善 MATLAB 代码
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4815498.html
Copyright © 2011-2022 走看看