216. Combination Sum III

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> tmp = new ArrayList<>();
        dfs(result, tmp, k, n, 1);
        return result;
    }
    private void dfs(List<List<Integer>> result, List<Integer> tmp, int size, int target, int start){
        if(target == 0 && tmp.size() == size){
            result.add(new ArrayList<>(tmp));
            return;
        }
        
        for(int i = start; i <= 9; i++){
            // pruning 
            if(i > target) return;
            tmp.add(i);
            dfs(result, tmp, size, target - i, i + 1); // every element used only once, hence i + 1
            tmp.remove(tmp.size() - 1);
        }
    }
}

 

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(res, new ArrayList<>(), k, n, 1, 0);
        return res;
    }
    private void dfs(List<List<Integer>> res, List<Integer> tmp, int k, int n, int start, int curSum){
        // base case 
        if(tmp.size() == k && curSum == n){
            res.add(new ArrayList<>(tmp));
            return;
        }
        if(tmp.size() > k || curSum > n) return;
        
        for(int i = start; i <= 9; i++){
            tmp.add(i);
            dfs(res, tmp, k, n, i + 1, curSum + i);
            tmp.remove(tmp.size() - 1);
        }
    }
}

 

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

 idea: every element can be used only once, so use a start index to record the current index, the next level starts at start index + 1

posted on 2018-07-18 08:07  猪猪&#128055;  阅读(85)  评论(0)    收藏  举报

导航