39. Combination Sum (not use befroe, so int I = start, dfs(i) -> is i !!

time: O(2^n), candidate choose or not choose, n times

space: O(target)

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        helper(res, new ArrayList<>(), candidates, target, 0);
        return res;
    }
    
    private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start) {
        if (target < 0) {
            return;
        } else if (target == 0) {
            res.add(new ArrayList<>(list));
        } else {
            for (int i = start; i < candidates.length; i++) {
                list.add(candidates[i]);
                helper(res, list, candidates, target - candidates[i], i); // pass i, why i = start => for seq search
                list.remove(list.size()-1);
            }
        }
        
    }
}

/*

7 - any of [],

7 = [2,3,6,7]

7 - 2 = 5

5 - 2 = 3

3 - 2 => no, 3 - 3 ok! backtrack



*/

why we cant just use for (i = 0..., because it should pass "the current index

and pass i, means we can reuse the same number

backtracking, we always have a tree (ex: [2, 3, 6, 7]), then cut and find the ans.

[2, 3, 6, 7]

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(result, candidates, target, new ArrayList<>(), 0);
        return result;
    }
    private void dfs(List<List<Integer>> result, int[] candidates, int target, List<Integer> list, int start) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(list));
            return;
        }
        // if every time from i = 0, will generate like [2,2,3] [2,3,2], [3,2,2]
        // just use order seq to pass the i index
        for (int i = start; i < candidates.length; i++) {
            list.add(candidates[i]);
            dfs(result, candidates, target - candidates[i], list, i);
            list.remove(list.size()-1);
        }
    }
}

ๆƒณ่ฆ้ฟๅ…้€™็จฎ็‹€ๆณ, ่จ˜ๅพ— use i = start, ไธฆไธ”ๅ‚ณๅ…ฅ i, ้€™ๆจฃๅฏไปฅไฟ่ญ‰ๅ‚ณๅ…ฅ i ็š„้ †ๅบๆ˜ฏๅฐ็š„, ๅฐฑไธๆœƒๆœ‰้‡่ค‡ๅ•้กŒ

ๆœƒๆŒ็บŒๅ…ˆ็”จ 2 ไพ† try, ็›ดๅˆฐไธ่กŒๅ†้–‹ๅง‹้€€ๅ›ž (ๆ‰€ไปฅไนŸๆ˜ฏ็‚บไป€้บผ < target ่ฆ return), ๅƒ้€™ๅ€‹ๆœ€ๅทฆ้‚Š็š„ไพ‹ๅญ

็•ถ็„ถ target == 0 ๆ™‚ๅฐฑๆœƒ็ด€้Œ„ไธ‹ไพ†็ตๆžœ

2้ƒฝ try ้ŽๅคšๆฌกๅพŒ, ๅˆฐๆœ€ๅทฆ้‚Š็š„ -1 ไบ†, ้€€ๅ›ž, ๆ‰ๆœƒ้–‹ๅง‹็”จ 3 ไพ† try ๏ผˆๆ‰€ไปฅๅˆ†ๆ”ฏๅฐฑๅพž-3 ้–‹ๅง‹็”จไบ†, -2 ๅฐฑไธๆœƒๅœจ็”จไบ†

ๆ‰€ไปฅ้€™ๆจฃๅฐฑ่ƒฝไฟ่ญ‰้ƒฝๅ…ˆ็”จ 2 ๅœจ็”จ 3... ๆ‰€ไปฅๅฏไปฅๅพ—ๅˆฐ [2,2,3]

ๅฆ‚ๆžœ็”จ i = 0

็ตๆžœ [2,2,3] [2,3,2], [3,2,2] =>  ๅฆ‚ๆžœ็”จ i = 0, ๆœƒ

ๅฐฑๆ˜ฏๆฏๆฌกๅ›บๅฎš้ƒฝ็”จ 4ๅ€‹ๅˆ†ๆ”ฏๅŽป try

5 . 4 1 . 0 4

-2 . -3 -2

3 2 x x 2 => -2 => [2,3,2] 2 => -2 => [3,2,2]

.-2 => [2,2,3]

้€™ๆจฃๅพ—ๅˆฐๅฐฑๆ˜ฏๆœƒๅ…ถๅฏฆๆœ‰้‡่ค‡

Last updated