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)
            }
        }
    }
  • 相关阅读:
    排序——插入排序
    利用socket传文件
    Segmentation fault (core dumped)
    Linux网络编程
    3G功能设计及实现
    rpm命令
    安装包相互依赖的问题
    centos网站(一些软件的下载)
    解决vim显示中文的问题
    glGetFloatv (GL_MODELVIEW_MATRIX, mat)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12972117.html
Copyright © 2011-2022 走看看