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

    题目:

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

    说明:

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

    示例 1:

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

    示例 2:

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

    解题:

    class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new ArrayList<>();
            //List<Integer> cur = new ArrayList<>();
            helper(res, new ArrayList<>(), k, n, 1);
            return res;
        }
        
        private void helper(List<List<Integer>> res, List<Integer> cur, int k, int target,
                           int start)
        {
            // exit condition
            if (target == 0 && k == 0)
                res.add(new ArrayList<Integer>(cur));
            else
            {
                for (int i = start; i < 10; i++)
                {
                    // prune
                    if (target < i) continue;
                    else
                    {
                        cur.add(i);
                        // set next to i + 1 to avoid duplicate
                        helper(res, cur, k - 1, target - i, i + 1);
                        cur.remove(cur.size() - 1);
                    }
                }
            }
        }
    }
  • 相关阅读:
    terminal下历史命令自动完成功能history auto complete
    Shell中while循环的done 后接一个重定向<
    python 链接hive
    shell 学习基地
    c++ 获取本地ip地址
    c++ 如何实现,readonly
    c++ 语法
    c++ 信号量
    vim插件介绍
    c++ memset 函数 及 坑
  • 原文地址:https://www.cnblogs.com/yanhowever/p/10870313.html
Copyright © 2011-2022 走看看