216. 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.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

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]]
class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList();
        int[] nums = {1,2,3,4,5,6,7,8,9};
        help(res, new ArrayList(), n, 0, 0, nums,  k);
        return res;
    }
    
    public void help(List<List<Integer>> res, List<Integer> cur, int target, int sum, int start, int[] nums, int k) {
        if(sum > target || cur.size() > k) return;
        if(cur.size() == k && sum == target) {
            res.add(new ArrayList(cur));
            return;
        }
        
        for(int i = start; i < nums.length; i++) {
            sum += nums[i];
            cur.add(nums[i]);
            help(res, cur, target, sum, i + 1, nums, k);
            sum -= nums[i];
            cur.remove(cur.size() - 1);
        }
    }
}

 

posted @ 2019-09-23 04:03  Schwifty  阅读(143)  评论(0编辑  收藏  举报