zoukankan      html  css  js  c++  java
  • [Leetcode 99] 40 Combination Sum II

    Problem:

    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] 

    Analysis:

    This is a dfs problem. First sort the given array to keep the element ordered. Then use dfs to search for candidate solutions. 

    After get a solution that sum is equal to taget. Before push it into the result vector. first need to check whether there is already a duplicated solution in the result vector. If not, then we are safe to add it into the result vector.

    Code:

     1 class Solution {
     2 public:
     3 vector<vector<int> > res;
     4 vector<int> t_res;
     5 int t;
     6 
     7 vector<vector<int> > combinationSum2(vector<int> &num, int target) {
     8     // Start typing your C/C++ solution below
     9     // DO NOT write int main() function
    10     res.clear();
    11     t_res.clear();
    12     t = target;
    13 
    14     if (num.size() == 0) return res;
    15 
    16     sort(num.begin(), num.end());
    17 
    18     dfs(0, 0, num);
    19 
    20     return res;
    21 }
    22     
    23 private:
    24     bool dup() {
    25 
    26     for (int i=0; i<res.size(); i++) {
    27         if(res[i].size() == t_res.size()) {
    28             int j;
    29             for (j=0; j<res[i].size(); j++) {
    30                 if (res[i][j] != t_res[j])
    31                     break;
    32             }
    33 
    34             if (j == res[i].size())
    35                 return true;
    36         }
    37     }
    38 
    39     return false;
    40 }
    41 
    42 void dfs(int idx, int sum, vector<int> &num) {
    43     if (sum == t && !dup()) {
    44         res.push_back(t_res);
    45         return ;
    46     } else if (sum > t)
    47         return ;
    48 
    49     for (int i=idx; i<num.size(); i++) {
    50         t_res.push_back(num[i]);
    51         dfs(i+1, sum+num[i], num);
    52         t_res.pop_back();
    53     }
    54 }
    55 };
    View Code
  • 相关阅读:
    第五周学习进度报告
    第四周学习进度报告
    第三周大数据学习进度
    十六周总结
    程序员修炼之道-从小工到专家阅读笔记03
    第二阶段冲刺10
    利用正则表达式,分割地址至省市县,更新MySQL数据库数据
    阅读笔记--《大型网站技术架构》—01大型网站概述
    第三周周总结——kettle的简单使用以及MYSQL数据库去重
    热词分析中运用可用性战术
  • 原文地址:https://www.cnblogs.com/freeneng/p/3242288.html
Copyright © 2011-2022 走看看