leecode---39---数组,dfs,回溯法---求所有的组合为target,数字无重复

给了个数组和目标值,要找到几个数字和为目标值。
dfs的时候入参有:总结果,当前数字记录,当前数字总和,数组,数组下标,目标值。
如果当前总和超过target,退出dfs
如果当前总和==target,记录结果
 
 

 
 
题意
给一个数组和target,求全部组合,其中数字可以重复使用,数组中没有重复数字
 
分析
 
 
 
代码
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        if(candidates == null || candidates.length <= 0 || target < 0) return result;
        dfs(result,temp,candidates,0,0,target);
        return result;
    }
    
    public void dfs(List<List<Integer>> result,List<Integer> temp,int[] nums,int pos,int curSum,int target){
        //1.直接退出循环情况
        if (curSum > target) return;
        
        //2.结果情况
        if (curSum == target) {
            result.add(new ArrayList<Integer>(temp));
        }
        
        //3.普通情况---选择条件:因为数字可以重复使用且无重复,所以从pos到末尾都可以用
        //4.是否回溯---因为记录了路程,所以进行下一种选择的时候需要把上一种选择剔除掉。
        for (int i=pos; i < nums.length; i++) {
            temp.add(nums[i]);
            curSum+=nums[i];
            dfs(result,temp,nums,i,curSum,target);
            temp.remove(temp.size() - 1);
            curSum -= nums[i];
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/buptyuhanwen/p/8985585.html