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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
    • The solution set must not contain duplicate combinations.

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

    题意:给定数T,在数组C中找到等于T的组合。元素可以重复利用。

    思路:这题的思想和combination sum ii 基本是一样的,就是要注意的是,某一个元素本身可以重复利用,这就导致了下次深搜不是从该元素的下一个元素开始,应该是从该元素本身开始。

    代码如下:

     1 class Solution {
     2 public:
     3     vector<vector<int> > combinationSum(vector<int> &candidates, int target) 
     4     {
     5         vector<vector<int>> res;
     6         vector<int> midVal;
     7         sort(candidates.begin(),candidates.end());
     8         DFS(res,midVal,candidates,target,0);
     9         return res;    
    10     }
    11 
    12     void DFS(vector<vector<int>> &res,vector<int> &midVal,vector<int> &candidates,int target,int start)
    13     {
    14         if(target<0)
    15             return;
    16         else if(target==0)
    17             res.push_back(midVal);
    18         else
    19         {
    20             for(int i=start;i<candidates.size();i++)
    21             {
    22                 
    23                 midVal.push_back(candidates[i]);
    24                 DFS(res,midVal,candidates,target-candidates[i],i);  // i
    25                 midVal.pop_back();
    26             }
    27         }
    28     }
    29 };
  • 相关阅读:
    css清除select默认的样式
    网站性能优化的方法--Yahoo
    jQuery写toTop(回到顶部)效果
    jquery的addClass、removeClass、toggleClass方法
    css选择器汇总
    日期对象的正确写法
    顶会热词统计
    《人月神话》读后感二
    新闻详情页实现
    第八周总结
  • 原文地址:https://www.cnblogs.com/love-yh/p/7151005.html
Copyright © 2011-2022 走看看