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 }
  • 相关阅读:
    Xpath语法与lxml库的用法
    Selenium--使用参考
    PhantomJS的替代品--无头浏览器(Headless Chrome)
    为什么只有一个元素的tuple要加逗号?
    反爬利器--设置代理服务器
    LeetCode 221. 最大正方形 | Python
    LeetCode 572. 另一个树的子树 | Python
    LeetCode 98. 验证二叉搜索树 | Python
    LeetCode 45. 跳跃游戏 II | Python
    LeetCode 25. K 个一组翻转链表 | Python
  • 原文地址:https://www.cnblogs.com/hhboboy/p/5857345.html
Copyright © 2011-2022 走看看