L216 Combination Sum III

Problem

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]]
  • k是一个组合共有几个数,n是这些数的总和

Solution:

public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    if(n <= 0 || k > n) return ans;
    List<Integer> list = new ArrayList<>();
    dfs(ans, list, k, n, 1);
    return ans;
}
private void dfs(List<List<Integer>> ans, List<Integer> list, int k, int n, int index){
    if(n < 0 || list.size() > k) return;
    if(list.size() == k && n == 0){
        ans.add(new ArrayList<>(list));
        return;
    }
    for(int i = index; i<= 9; i++ ){
        list.add(i);
        dfs(ans, list, k ,n - i, i + 1);
        list.remove(list.size() - 1);
        
    }
}

Last updated

Was this helpful?