zoukankan      html  css  js  c++  java
  • DFS_216. 组合总和 III

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

    说明:

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

    输入: k = 3, n = 7
    输出: [[1,2,4]]

    示例 2:

    输入: k = 3, n = 9
    输出: [[1,2,6], [1,3,5], [2,3,4]]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum-iii


    思路:

    懂了一和二(前面已经做过一和二了这是三,变种),再来再多3456789都不怕

    还是一样的用DFS,变了的是给定的数字是1-9的正整数之间呗

    不能重复呗,盘他

    class Solution {
        public static List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new LinkedList<>();
            
            if (n == 0){
                return res;
            }
            
            Deque<Integer> path = new ArrayDeque<>();
            
            dfs(k,n,path,res,1);
            return res;
        }
    
        private static void dfs(int k, int n, Deque<Integer> path, List<List<Integer>> res,int first) {
            if (k == 0 && n == 0){
                res.add(new ArrayList<>(path));
                return;
            }
            if (k == 0 || n == 0) {
                return;
            }
            for (int i = first; i <= 9; i++) {
                path.add(i);
                dfs(k - 1 , n - i , path, res,i + 1);
                path.remove(i);
            }
        }
    }
  • 相关阅读:
    Unix进程和线程管理及其异同
    UnixIPC之共享内存
    Unix/Linux常用文件操作
    java中int和Integer比较
    JAVA四种引用类型
    JAVA-Exception&Error
    JAVA特性-跨平台/面向对象
    JAVA单向链表实现
    linux安装及配置c++的opencv库
    static_cast、const_cast、dynamic_cast、reinterpret_cast
  • 原文地址:https://www.cnblogs.com/zzxisgod/p/13373622.html
Copyright © 2011-2022 走看看