zoukankan      html  css  js  c++  java
  • 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] 

    public class Solution {
        public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
            int len = candidates.length;
            ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
            if(len == 0) return results;
            ArrayList<Integer> output = new ArrayList<Integer>();
            Arrays.sort(candidates);
            int sum = 0, depth = 0;
            DFS(candidates, depth, sum, target, output, results);
            return results;
        }
        
        public void DFS(int[] candidates, int depth, int sum, int target, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> results ){
            if(sum > target) return;
            if(sum == target){
                ArrayList<Integer> tmp = new ArrayList<Integer>();
                tmp.addAll(output);
                results.add(tmp);
                return;
            }
            if(sum < target){
                for(int i = depth; i < candidates.length; i++){
                    sum += candidates[i];
                    output.add(candidates[i]);
                    DFS(candidates, i, sum, target, output, results);
                    output.remove(output.size()-1);
                    sum -= candidates[i];
                }
            }
        }
    }
  • 相关阅读:
    所有蚂蚁掉下来前的最后一刻
    最长有效括号
    n的第k个因子--leetcode1492
    删掉一个元素以后全为1的最长子数组。
    public class和class的区别
    数据库中的乐观锁和悲观锁以及实现方式
    HashMap底层实现原理 扩容机制
    jvm 内存泄漏现象和处理方案
    Django模板标签语法
    Django图片的上传与下载
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3538551.html
Copyright © 2011-2022 走看看