zoukankan      html  css  js  c++  java
  • [Leetcode] 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.
    • 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 2,3,6,7 and target 7
    A solution set is: 
    [7] 
    [2, 2, 3] 

    DFS!

     1 class Solution {
     2 public:
     3     void findNext(vector<vector<int> > &res, vector<int> &candidates, vector<int> v, int sum, int target, int idx) {
     4         if (sum > target || idx >= candidates.size()) {
     5             return;
     6         }
     7         if (sum == target) {
     8             res.push_back(v);
     9             return;
    10         }
    11         v.push_back(candidates[idx]);
    12         findNext(res, candidates, v, sum + candidates[idx], target, idx);
    13         v.pop_back();
    14         findNext(res, candidates, v, sum, target, idx + 1);
    15     }
    16     
    17     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
    18         vector<vector<int> > res;
    19         sort(candidates.begin(), candidates.end());
    20         vector<int> v;
    21         findNext(res, candidates, v, 0, target, 0);
    22         return res;
    23     }
    24 };
  • 相关阅读:
    opennebula 编译日志
    eclipse scons 使用指南
    eclipse 安装scons
    在Windows7上搭建Cocos2d-x 3.2alpha0开发环境
    Centos6.3 jekyll环境安装
    CNN-利用1*1进行降维和升维
    偏导数
    卷积神经网络--CNN
    struts2 模型驱动
    Struts2 数据驱动
  • 原文地址:https://www.cnblogs.com/easonliu/p/3641628.html
Copyright © 2011-2022 走看看