zoukankan      html  css  js  c++  java
  • 39. Combination Sum

    package LeetCode_39
    
    /**
     * 39. Combination Sum
     * https://leetcode.com/problems/combination-sum/description/
     *
     * Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
    The same repeated number may be chosen from candidates unlimited number of times.
    
    Note:
    All numbers (including target) will be positive integers.
    The solution set must not contain duplicate combinations.
    
    Example 1:
    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
    [7],
    [2,2,3]
    ]
     * */
    class Solution {
        fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
            //bfs
            val result = ArrayList<ArrayList<Int>>()
            //candidates.sort()
            dfs(result, candidates, 0, ArrayList<Int>(), target)
            println(result)
            return result
        }
    
        private fun dfs(result: ArrayList<ArrayList<Int>>, candidates: IntArray, s: Int, cur: ArrayList<Int>, target: Int) {
            if (target == 0) {
                result.add(ArrayList(cur))
                return
            }
            for (i in s until candidates.size) {
                //pruning
                if (candidates[i] > target) {
                    return
                }
                cur.add(candidates[i])
                dfs(result, candidates, i, cur, target - candidates[i])
                cur.removeAt(cur.size - 1)
            }
        }
    }
  • 相关阅读:
    linux_shell_入门
    Linux下安装jdk
    Linux杂记
    Linux常用命令
    Java 性能优化的五大技巧
    Java异常处理的9个最佳实践
    Java面试:投行的15个多线程和并发面试题
    敏捷持续集成详解
    gitlab系列详解
    git系列讲解
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12972117.html
Copyright © 2011-2022 走看看