216. 组合总和 III

找出所有相加之和为 n 的 个数的组合组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

  • 所有数字都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

看成是77题和39题的合体就行了,不难的。

class Solution {
    private void backtrack(int[] candidates, int target,List<List<Integer>> res,List<Integer> path,int pos){
        if(target<0)
            return;
        if(target == 0){
            res.add(new ArrayList<Integer>(path));
            return;
        }
        for(int i=pos;i<candidates.length;i++){
            path.add(candidates[i]);
            backtrack(candidates,target-candidates[i],res,path,i);
            path.remove(path.size()-1);
        }
        
    }
    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList();
        List<Integer> path = new ArrayList();
        backtrack(candidates,target,res,path,0);
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/w8253497062015/article/details/82555739