leetcode39. 组合总和(回溯)

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]

代码

class Solution {
    List<List<Integer>> cList=new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        combinationS(candidates,target,new ArrayList<>());
        return cList;
    }
    public void combinationS(int[] candidates, int target,List<Integer> temp) {

        if(target==0)//找到满足条件的序列
        {
            cList.add(new ArrayList<>(temp));
            return;
        }
        
        for(int i=0;i<candidates.length;i++)
        {
          
            if(target<candidates[i]||temp.size()>0&&candidates[i]<temp.get(temp.size()-1))continue;//通过筛选升序的序列去重
            temp.add(candidates[i]);
           
            combinationS(candidates,target-candidates[i],temp);
         
            temp.remove(temp.size()-1);//回溯
        }
        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44560620/article/details/107758748
今日推荐