Monday, February 6, 2017

Leetcode -- 216. Combination Sum III (Backtracking)

216. Combination Sum III (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.

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]]
思路: use backtracking to find all possible solutions.
Complexity: Time O(9!) - total possibilities Space O(9) stack

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>> ();
        dfs(1, n, k, new ArrayList(), res);
        return res;
    }
    
    private void dfs(int start, int n, int k, List<Integer> path, List<List<Integer>> res){
        if(path.size() == k){
            if(n == 0)res.add(new ArrayList(path));
            return;
        }
        for(int i = start; i <= 9; i++){//digits from 1 to 9
            path.add(i);
            dfs(i + 1, n - i, k, path, res);
            path.remove(path.size() - 1);
        }
    }
}

No comments:

Post a Comment