美文网首页
2020-05-02 216. Combination Sum

2020-05-02 216. Combination Sum

作者: _伦_ | 来源:发表于2020-05-02 09:50 被阅读0次

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

All numbers will be positive integers.

The solution set must not contain duplicate combinations.

Example 1:

Input:k= 3,n= 7Output:[[1,2,4]]

Example 2:

Input:k= 3,n= 9Output:[[1,2,6], [1,3,5], [2,3,4]]

有个trick: (2 * i + k - 1) / 2 <= n

因为不这样提前判断好,会浪费时间做一些不必要的遍历

注意进入下一层遍历的时候,n取n-i,k取k-1

class Solution {

    public List<List<Integer>> combinationSum3(int k, int n) {

        List<List<Integer>> res = new LinkedList<>();

        List<Integer> cur = new ArrayList<>();

        backtrace(cur, res, k, n, 1);

        return res;

    }

    private void backtrace(List<Integer> cur, List<List<Integer>> res, int k, int n, int start) {

        if (n <= 0 || k <= 0) {

            if (n == 0 && k == 0) res.add(new ArrayList<>(cur));

            return;

        }

        for (int i = start; i <= 9 && (2 * i + k - 1) / 2 <= n; i++) {

            cur.add(i);

            backtrace(cur, res, k - 1, n - i, i + 1);

            cur.remove(cur.size() - 1);

        }

    }

}

相关文章

  • 2019-01-26

    LeetCode 216. Combination Sum III Description Find all po...

  • 递归与排列组合

    216. Combination Sum III(https://leetcode.com/problems/co...

  • 216. Combination Sum III

    216. Combination Sum III Total Accepted: 38518Total Submi...

  • 2020-05-02 216. Combination Sum

    Find all possible combinations ofknumbers that add up to ...

  • Instantiation of List (Java)

    动机 今天刷Leetcode时碰到的一道问题(216. Combination Sum III): Find al...

  • Leetcode 【216、769】

    题目描述:【DFS】216. Combination Sum III 解题思路: 这道题一看要求输出所有满足题意的...

  • 216. Combination Sum III

    这道题目在微软现场面中遇到了,当年太傻没做出来,其实思路很简单,就是回溯,但是要注意回溯的树的树杈越来越少,代码如下:

  • 216. Combination Sum III

    Find all possible combinations ofknumbers that add up to ...

  • 216. Combination Sum III

    题目 分析 这道题和之前的Combination Sum I II类似,都可以用回溯解法。回溯解法的套路是: ch...

  • 216. Combination Sum III

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

网友评论

      本文标题:2020-05-02 216. Combination Sum

      本文链接:https://www.haomeiwen.com/subject/gmnhghtx.html