zoukankan      html  css  js  c++  java
  • 39. Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    For example, given candidate set [2, 3, 6, 7] and target 7
    A solution set is: 

    [
      [7],
      [2, 2, 3]
    ]
    采用深度优先搜索的思想,对于输入candidates=[1,2] ,target=3,遍历的方向如图: 

    这里写图片描述

    
    
     1 #include "stdafx.h"
     2 
     3 #include <iostream>
     4 #include <vector>
     5 #include <algorithm>
     6 
     7 using namespace std;
     8 void helper(int pos, int base, int target, vector<int>& candidates, vector<int>& path, vector<vector<int> >& result)
     9 {
    10     if (base > target)
    11         return;
    12     if (base == target)
    13     {
    14         result.push_back(path);
    15         return;
    16     }
    17     for (int i = pos; i < candidates.size(); ++i)
    18     {
    19         path.push_back(candidates[i]);
    20         helper(i, base + candidates[i], target, candidates, path, result);
    21         path.pop_back();
    22     }
    23 
    24 }
    25 vector<vector<int> > combinationSum(vector<int>& candidates, int target)
    26 {
    27     vector<vector<int> > result;
    28     vector<int> path;
    29     sort(candidates.begin(), candidates.end());
    30     vector<int>::iterator it = unique(candidates.begin(),candidates.end());
    31     candidates.erase(it, candidates.end());
    32     helper(0, 0, target, candidates, path, result);
    33     return result;
    34 }
    35 int main()
    36 {
    37     vector<vector<int> > result;
    38     vector<int> candidates;
    39     candidates.push_back(2);
    40     candidates.push_back(2);
    41     candidates.push_back(3);
    42     candidates.push_back(7);
    43     int target = 7;
    44     result = combinationSum(candidates, target);
    45 
    46     return 0;
    47 }
  • 相关阅读:
    s111 stark组件
    数据结构
    django基础
    15个值得开发人员关注的jQuery开发技巧和心得
    关于浏览器事件的思考
    关于浏览器事件的思考
    浅入javascript正则表达式的规则.
    JQuery常用功能的性能优化
    vim
    常用免费的WebService列表
  • 原文地址:https://www.cnblogs.com/hhboboy/p/5857345.html
Copyright © 2011-2022 走看看