huimeich / leetcode-solution

0 stars 0 forks source link

Combination Sum III #110

Open huimeich opened 8 years ago

huimeich commented 8 years ago

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

huimeich commented 8 years ago
public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> soFar = new ArrayList<Integer>();
        combHelper(k,n,res,soFar);
        return res;
    }
    public void combHelper(int k, int n, List<List<Integer>> res, List<Integer> soFar){
        if (k == 0 && n == 0) {
            res.add(new ArrayList<Integer>(soFar));
            return;
        }
        if (k <= 0 || n <= 0) {
            return;
        }
        int i;
        if (soFar.isEmpty()) i = 1;
        else i = soFar.get(soFar.size()-1) + 1;
        for (; i <= n && i < 10; i++){
            soFar.add(i);
            combHelper(k-1,n-i,res,soFar);
            soFar.remove(soFar.size()-1);
        } 
        return;
    }
}