39 combination sum

https://leetcode.com/problems/combination-sum/submissions/

ๆณจๆ„่ฟ™้‡Œๅไธๆ˜ฏ็ซ‹้ฉฌๅ๏ผŒๆ˜ฏaddๅฎŒไน‹ๅŽๅ†ๅ๏ผŒๅŒๆ—ถๆณจๆ„็”จ.subList(presize, size).clear()็š„็ฅžๅฅ‡ๅๆณ•

class Solution {
     List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(candidates, 0, new ArrayList<>(), target, 0);
        return ans;
    }
    private void dfs(int[] candidates, int index, List<Integer> path, int target, int sum) {
        if (sum > target) return;
        if (sum == target) {
            ans.add(new ArrayList<>(path));
            return;
        }
        if (index == candidates.length) {
            return;
        }
        dfs(candidates, index + 1, path, target, sum);
        int presize = path.size();
        while (sum < target) {
            sum += candidates[index];
            path.add(candidates[index]);
            dfs(candidates, index + 1, path, target, sum);
        }
        path.subList(presize, path.size()).clear();
    }
}

Last updated