LeetCode39:组合总和

题目:

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

思路:

  • 回溯法
  • 选择当前数。添加到组合列表中。递归。回溯

代码:

class Solution {



    public List<List<Integer>> combinationSum(int[] candidates, int target ) {
        List<List<Integer>> resultList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        dfs(candidates, target, resultList, list, 0);
        return resultList;
    }

    public void dfs(int[] candidates, int target, List<List<Integer>> resultList, List<Integer> list,  int idx) {
        //如果遍历完了数组,就结束
        if (idx == candidates.length) {
            return;
        }

        //达到了目标值,就添加到结果列表中
        if (target == 0) {
            resultList.add(new ArrayList<>(list));
            return;
        }
        //在决策中,可以选择跳过不用第 idx 个数。也可以选择像后面代码,选择第 idx 个数
        dfs (candidates, target , resultList, list, idx+1);

        // 如果已经大于我们所需的target 值,说明已经不满足条件了。终止递归。
        if (target - candidates[idx] >=0) {
            //选择第 idx 个数。添加到列表中
            list.add( candidates[idx]);
            //递归。目标值去掉已经添加的值
            dfs (candidates, target-candidates[idx] , resultList, list, idx);
            //回溯
            list.remove( list.size()-1);           

        }
 
    }


}
上一篇:Python学习


下一篇:数据结构——优先级队列(堆)