DFS_39. 组合总和

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

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

说明:

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

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


示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum


思路:

已经刷了好多DFS的题,都是差不多的,手感越来越好

第一步:这题没有什么特殊情况排除

第二步:建立基础遍历,一个记录最终的返回值,一个记录当前的路径上的值,一个记录判断到第几个值了

第三步:dfs每次向下都是用给定的值减去给定数组中的值,可以重复利用,所以不同判断是否已经用过,记录的条件是减到最后的值为0

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //记录最终的返回值
        List<List<Integer>> res = new LinkedList<>();
        //记录当前情况下的路径
        Deque<Integer> path = new ArrayDeque<>();
        int len = candidates.length;
        Arrays.sort(candidates);
        dfs(len,target,0,candidates,path,res);
        return res;
    }

    private void dfs(int len, int target, int first, int[] candidates, Deque<Integer> path, List<List<Integer>> res) {
        if (target == 0){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = first; i < len; i++) {
            if (target < candidates[i]){
                continue;
            }
            path.add(candidates[i]);
            dfs(len,target - candidates[i],i,candidates,path,res);
            path.remove(candidates[i]);
        }
    }
}
原文地址:https://www.cnblogs.com/zzxisgod/p/13373020.html