Thursday, October 15, 2015

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.
Ensure that numbers within the set are sorted in ascending order.

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: recursion
类似于 Combination Sum 和 Combination Sum II
public class Solution {
    public List> combinationSum3(int k, int n) {
        List> res = new ArrayList>();
        List list = new ArrayList();
        if (n == 0) {
            list.add(0);
            res.add(list);
            return res;
        }
        
        helper(res, list, k, n, 1);
        return res;
    }
    
    public void helper(List> res, List list, int k, int n, int start) {
        if (n < 0) {
            return;
        }
        
        if (n == 0 && k == 0) {
            res.add(new ArrayList(list));
            return;
        }
        
        for (int i = start; i <= 9; i++) {
            list.add(i);
            k--;
            helper(res, list, k, n - i, i + 1);
            list.remove(list.size() - 1);
            k++;
        }
    }
}

No comments:

Post a Comment