๐ŸŒ• 40. ็ป„ๅˆๆ€ปๅ’Œ II

ๅžไฝ›็ซฅๅญ2022ๅนด6ๆœˆ9ๆ—ฅ
  • algorithm
  • backtrace
ๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ• 40. ็ป„ๅˆๆ€ปๅ’Œ II

้šพๅบฆ: ๐ŸŒ•

้—ฎ้ข˜ๆ่ฟฐ

img_11.png


่งฃๆณ•

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // ๆ€่ทฏ๏ผš
        // ๅฏ้‡ๅคๆ•ฐ็ป„ + ๆ— ้‡ๅค้€‰ๅ–
        Arrays.sort(candidates);
        int len = candidates.length;
        LinkedList<Integer> path = new LinkedList<>();
        mySol(candidates, target, len, 0, 0, path);
        return res;
    }

    private void mySol(int[] candidates, int target, int len, int index, int sum, LinkedList<Integer> path) {
        // ้€’ๅฝ’็ปˆๆญขๆกไปถ
        if(sum > target) {
            return;
        }
        if(sum == target) {
            res.add(new LinkedList<>(path));
            return;
        }
        if(index > len) {
            return;
        }
        for(int i = index; i < len; i ++) {
            if(sum + candidates[i] > target) {
                return;
            }
            // ๅฝ“ๅ‰ๆž่‹ฅๅ‰ไธ€ไธชๅ…ƒ็ด ๅทฒ็ป่ขซ้€‰ๅ–๏ผŒๅˆ™ๅฝ“ๅ‰ๆžไธๅญ˜ๅœจ
            if(i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.addLast(candidates[i]);
            mySol(candidates, target, len, i + 1, sum + candidates[i], path);
            path.removeLast();
        }
    }
}

่พ“ๅ‡บ

img_10.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/6/20 ไธ‹ๅˆ8:24:47
่ดก็Œฎ่€…: liuxianzhishou