leetcode_39_组合总和@@dfs

在这里插入图片描述

class Solution {
    
	int sum;
   	int[] nums;
	int tempSum;
	List<List<Integer>> list=new ArrayList<List<Integer>>();
	List<Integer> tempList=new ArrayList<Integer>();

	public List<List<Integer>> combinationSum(int[] candidates, int target) {
		if(candidates.length==0) return list;
		this.nums=candidates;
		this.sum=target;
        //Arrays.sort(nums);
		dfs(0);
		return list;

	}

	private void dfs(int idx) {
		if(tempSum>=sum) {
			if(tempSum==sum) {
				list.add(new ArrayList<Integer>(tempList));
			}
			return;
		}
		
		for (int i = idx; i < nums.length; i++) {
            if(tempSum+nums[i]>sum) continue;
			tempSum+=nums[i];
			tempList.add(nums[i]);
			dfs(i);
			tempSum-=nums[i];
			tempList.remove(tempList.size()-1);
		}	
	}
}

猜你喜欢

转载自blog.csdn.net/ruochen82155551/article/details/107634533