leetcode刷题(数组list回溯法)19—组合总和

39. 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。

class Solution {
    
    
    // 执行用时:4 ms, 在所有 Java 提交中击败了55.57%的用户
    // 内存消耗:39.7 MB, 在所有 Java 提交中击败了94.57%的用户
    // 回溯法
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
    
    
        Deque<Integer> dp = new ArrayDeque<>();
        int len = candidates.length;
        List<List<Integer>> res  = new ArrayList<>();
        if(len == 0)
            return res;
        DP(candidates,len, target, dp, res);
        return res;
    }
   
     public void DP(int[] candidates,int n, int target, Deque<Integer> dp,List<List<Integer>> res) {
    
    
         //dp[n,k],当n=0时,返回当前数组中的数
        if(target == 0){
    
    
            res.add(new ArrayList<>(dp));
            return;
        }
        if(n == 0)
            return;
        int times = target / candidates[n - 1];
        for(int i = 0;i <= times;++i){
    
    
            for(int j = 0; j < i; ++j){
    
    
                dp.addLast(candidates[n - 1]);
            }
            DP(candidates, n - 1,target - candidates[n - 1] * i, dp,res);
            // 状态重置
            for(int j = 0; j < i; ++j){
    
    
                dp.removeLast();
            }
        }
    }
}

おすすめ

転載: blog.csdn.net/qq_38754625/article/details/108521901