216. Combination Sum III

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.

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]]

My Solutions:

和combination sum类似,除了remain == 0,多加一个temp.size() == k 的条件

注意function dfs里dfs到下一次是i+1, 因为一个数字只能加一次

 class Solution {   
     public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> list = new ArrayList<>();
        dfs(list, new ArrayList<Integer>(), k, n, 1);
        return list;
    }
    
    public void dfs(List<List<Integer>> list, List<Integer> temp, int k, int remain, int start) {
        if (remain < 0) return;
        
        if (temp.size() == k && remain == 0) {
            list.add(new ArrayList<Integer>(temp)); 
            return; // 满足条件直接返回
        } 
        
        for (int i = start; i <= 9; i++){
            temp.add(i);
            dfs(list, temp, k, remain - i , i + 1); // 这里用下一个数字i + 1
            temp.remove(temp.size() - 1);
        }
    }
}

Last updated