2016年7月21日星期四

[LeetCode] #216 Combination Sum III

Time complexity: O(2^n)

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        if (k < 1 || n < 1 || n > 45) {
            return result;
        }
        helper(result, new ArrayList<Integer>(), 0, k, n, 1); // Attn: starts from 1, not 0 
        return result;
    }
    
    private void helper(List<List<Integer>> result, List<Integer> path, int sum, int k, int n, int start) {
        if (path.size() == k && sum == n) {
            result.add(new ArrayList<Integer>(path));
            return;
        }
        if (path.size() == k) {
            return;
        }
        for (int i = start; i <= 9; i++) {
            if (sum + i > n) {
                break;
            }
            path.add(i);
            helper(result, path, sum + i, k, n, i + 1);
            path.remove(path.size() - 1);
        }
    }
}


没有评论:

发表评论