zoukankan      html  css  js  c++  java
  • leetcode------Combination Sum

    标题: Combination Sum
    通过率: 27.7%
    难度: 中等

    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 (a1, a2, … , 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] 

    本题依然是递归算法,算法的关键点是递归时重复元素。题目上说可以从candidate中重复一个元素,那么再递归时不用从i+1开始,还是从i开始,结果还可能是重复的情况,那么还是要res。cantain一次,具体细节看代码:

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
     3         ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
     4         ArrayList<Integer> tmp=new ArrayList<Integer>();
     5         Arrays.sort(candidates);
     6         dfs(candidates,target,0,res,tmp);
     7         return res;
     8     }
     9     public void dfs(int[] candidates, int target,int start,ArrayList<ArrayList<Integer>> res,ArrayList<Integer> tmp){
    10         if(target<0)return;
    11         if(target==0 && !res.contains(tmp)){
    12             res.add(new ArrayList<Integer>(tmp));
    13             return ;
    14         }
    15         for(int i=start;i<candidates.length;i++){
    16             tmp.add(candidates[i]);
    17             dfs(candidates,target-candidates[i],i,res,tmp);
    18             tmp.remove(tmp.size()-1);
    19         }
    20     }
    21 }
  • 相关阅读:
    c++单例设计模式---17
    c++友元函數---16
    c++const关键字---15
    c++浅拷贝和深拷贝---14
    linux shell 基本语法
    Linux静态库生成
    alsa wav
    Android Butterknife使用方法总结 IOC框架
    利用cglib给javabean动态添加属性,不用在建VO
    钢铁雄心三 通过事件做修改器
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4354379.html
Copyright © 2011-2022 走看看