【算法刷题day27】Leetcode:39. 组合总和、40. 组合总和 II、131. 分割回文串-Leetcode 39. 组合总和

时间:2024-04-20 10:03:31

题目:39. 组合总和
解析:代码随想录解析

解题思路

还是回溯三部曲

代码

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> paths = new ArrayList<>();
    int curSum = 0;
    private void backtracking(int[] candidates, int target, int startIndex) {
        if (curSum >= target) {
            if (curSum == target)
                res.add(new ArrayList<>(paths));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            paths.add(candidates[i]);
            curSum += candidates[i];
            backtracking(candidates, target, i);
            paths.remove(paths.size() -1);
            curSum -= candidates[i];
        }
    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtracking(candidates, target, 0);
        return res;
    }
}

总结

越来越熟练了