Leetcode 216. 组合总和 III Combination Sum III - Java 以回溯法解题

class Solution {
    List> result = new ArrayList<>();
    LinkedList path = new LinkedList<>();
    
    public List> combinationSum3(int k, int n) {
        backtracking(n, 0, k, 1);
        return result;
    }
    public void backtracking(int targetSum, int sum, int k, int startIndex){
        
        if(path.size() == k){
            if(sum == targetSum){
                result.add(new ArrayList<>(path));
                return;
            }
            return;
        }

        for(int i = startIndex; i<= 9 - (k-path.size()) + 1; i++){
            sum += i;
            path.add(i);
            backtracking(targetSum, sum, k, i+1);
            sum -= i;
            path.removeLast();
        }
    }
}

记住剪枝操作:9 - (k-path.size()) + 1

你可能感兴趣的:(leetcode,java,算法)