216. Combination Sum III

Find all possible combinations ofknumbers that add up to a numbern, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

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

tag: DFS

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();

        dfs(k, n, 1, 0, new ArrayList<Integer>(), ans);

        return ans;
    }

    private void dfs(int k, int n, int index, int sum, List<Integer> path, List<List<Integer>> ans){
        if (path.size() == k){
            if (sum == n){
                ans.add(new ArrayList<Integer>(path));
            }
            return;
        }

        if (sum > n){
            return;
        }

        for (int i = index; i <= 9; i++){
            path.add(i);
            dfs(k, n, i + 1, sum + i, path, ans);
            path.remove(path.size() - 1);
        }
    }
}

results for ""

    No results matching ""