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)
            }
        }
    }
  • 相关阅读:
    maven settings
    java.util.Base64
    Centos 7 下 LAMP 部署
    Cisco N3K VPC+HSRP+ospf 配置
    centos 7 下多网卡绑定+ vlan 网卡配置
    centos 7 下 cobbler 安装
    hive0.12 rcfile gzip 测试
    Hive内部表外部表转化分析(装)
    hadoop2.2.0 + hbase 0.94 + hive 0.12 配置记录
    hbase 问题记录
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12972117.html
Copyright © 2011-2022 走看看