zoukankan      html  css  js  c++  java
  • LeetCode 216 组合总数III

    LeetCode 216 组合总数III

    问题描述:
    找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
    说明

    • 所有数字都是正整数。
    • 解集不能包含重复的组合。

    深度优先搜索DFS

    执行用时:1 ms, 在所有 Java 提交中击败了69.81%的用户
    内存消耗:37.2 MB, 在所有 Java 提交中击败了34.57%的用户

    class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            //边界情况
            if(k<=0 || n<=0 || n>k*9) {
                return new ArrayList<>();
            }
            //组合不能重复,每个数字只能用一次
            int[] candidates = new int[]{
                1,2,3,4,5,6,7,8,9
            };
            List<List<Integer>> results = new ArrayList<>();
            backtrace(results, new ArrayList<>(), candidates, -1, n, k);
            
            return results;
        }
    
        public void backtrace(List<List<Integer>> results, List<Integer> result, int[] candidates, int curr, int target, int k) {
            if(k==0 && target==0) {
                results.add(new ArrayList<Integer>(result));
                return;
            }
    
            for(int next=curr+1; next<candidates.length
                //剪枝
                &&candidates[next]<=target
                &&(candidates.length-next)>=k; next++) {
                result.add(candidates[next]);
                backtrace(results, result, candidates, next, target-candidates[next], k-1);
                result.remove(result.size()-1);
            }
    
            return;
        }
    }
    
  • 相关阅读:
    Golang之排序算法
    Golang之一个简单的聊天机器人
    golang之流程控制(注意点)
    golang之指针
    vs code中自动添加注释插件koroFileHeader
    stack栈、heap堆的说明图
    c语言中的数据类型的最大最小值
    数组问题:a与&a有的区别
    STM32F10x之NVIC
    大小端的另一种测试方法
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13649699.html
Copyright © 2011-2022 走看看