216. Combination Sum III

2020/01/12 Leetcode

216. Combination Sum III

Tags: ‘Array’, ‘Backtracking’

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 = 7
Output: [[1,2,4]]

Example 2:

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

Solution

backtracking 模板 59% 6%

public List<List<Integer>> combinationSum3(int k, int n) {
    int[] nums = {1,2,3,4,5,6,7,8,9};
    List<List<Integer>> result = new ArrayList<>();
    backtrack(result, new ArrayList<Integer>(), nums, k, n, 0);
    return result;
}

private void backtrack(List<List<Integer>> result, List<Integer> temp, int[] nums, int countRemain, int remain, int start) {
    // 结束条件
    if (countRemain == 0 && remain == 0) {
        result.add(new ArrayList<>(temp));
        return;
    } else if (remain < 0 || remain < 0) {
        return;
    }
    
    for (int i = start; i < nums.length; i++) {
        temp.add(nums[i]);
        backtrack(result, temp, nums, countRemain - 1, remain - nums[i], i + 1);
        temp.remove(temp.size() - 1);
    }
}

方法2,可以不用nums 59% 6%

public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> result = new ArrayList<>();
    backtrack(result, new ArrayList<Integer>(), k, n, 1);
    return result;
}

private void backtrack(List<List<Integer>> result, List<Integer> temp, int countRemain, int remain, int start) {
    // 结束条件
    if (countRemain == 0 && remain == 0) {
        result.add(new ArrayList<>(temp));
        return;
    } else if (remain < 0 || remain < 0) {
        return;
    }
    
    for (int i = start; i <= 9; i++) {
        temp.add(i);
        backtrack(result, temp, countRemain - 1, remain - i, i + 1);
        temp.remove(temp.size() - 1);
    }
}

Search

    Table of Contents