216. Combination Sum III

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了216. Combination Sum III相关的知识,希望对你有一定的参考价值。

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.


Example 1:

Input: k = 3, n = 7

Output:

 

[[1,2,4]]

 


Example 2:

Input: k = 3, n = 9

Output:

 

[[1,2,6], [1,3,5], [2,3,4]]

 

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        int nums[] = {1,2,3,4,5,6,7,8,9};
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> member = new ArrayList<>();
        dfs(res, member, 0, nums, n, k);
        return res;
    }
    public void dfs(List<List<Integer>> res, List<Integer> member, int deep, int[] nums, int n, int k){
        if(member.size() > k || n < 0) return;
        if(member.size() == k && n == 0) {
            res.add(new ArrayList<>(member));
            return;
        }
        for(int i = deep ; i < nums.length; i++){
            member.add(nums[i]);
            dfs(res, member, i+1, nums, n-nums[i], k);
            member.remove(member.size()-1);
        }
    }
}

 

以上是关于216. Combination Sum III的主要内容,如果未能解决你的问题,请参考以下文章

216 Combination Sum III 组合总和 III

216. Combination Sum III

216. Combination Sum III

[LeetCode] 216. Combination Sum III

leetcode [216]Combination Sum III

leetcode 216. Combination Sum III