leetcode *216. 组合总和 III

【题目】*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]]

【解题思路1】回溯剪枝

class Solution {
    
    
    public List<List<Integer>> combinationSum3(int k, int n) {
    
    
        List<List<Integer>> ans = new ArrayList<>();
        if(k > 9 || n < (1 + k) * k / 2 || n > (19 - k) * k / 2)    return ans;

        List<Integer> path = new ArrayList<>();
        dfs(1, k, n, ans, path);
        return ans;
    }

    public void dfs(int start, int k, int n, List<List<Integer>> ans, List<Integer> path) {
    
    
        if(n < 0)   return;

        if(k == 0 &&  n == 0) {
    
    
            ans.add(new ArrayList<>(path));
            return;
        }

        for(int i = start; i < 10; i++) {
    
    
            path.add(i);
            dfs(i + 1, k - 1, n - i, ans, path);
            path.remove(path.size() - 1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/XunCiy/article/details/108526734