LeetCode 216 组合总数III

LeetCode 216 组合总数III

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

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

深度优先搜索DFS

执行用时:1 ms, 在所有 Java 提交中击败了69.81%的用户
内存消耗:37.2 MB, 在所有 Java 提交中击败了34.57%的用户

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        //边界情况
        if(k<=0 || n<=0 || n>k*9) {
            return new ArrayList<>();
        }
        //组合不能重复,每个数字只能用一次
        int[] candidates = new int[]{
            1,2,3,4,5,6,7,8,9
        };
        List<List<Integer>> results = new ArrayList<>();
        backtrace(results, new ArrayList<>(), candidates, -1, n, k);
        
        return results;
    }

    public void backtrace(List<List<Integer>> results, List<Integer> result, int[] candidates, int curr, int target, int k) {
        if(k==0 && target==0) {
            results.add(new ArrayList<Integer>(result));
            return;
        }

        for(int next=curr+1; next<candidates.length
            //剪枝
            &&candidates[next]<=target
            &&(candidates.length-next)>=k; next++) {
            result.add(candidates[next]);
            backtrace(results, result, candidates, next, target-candidates[next], k-1);
            result.remove(result.size()-1);
        }

        return;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13649699.html