๐ŸŒ• 216. ็ป„ๅˆๆ€ปๅ’Œ III

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

๐ŸŒ• 216. ็ป„ๅˆๆ€ปๅ’Œ III

้šพๅบฆ: ๐ŸŒ•

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

img_4.png


่งฃๆณ•

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        // ๆ€่ทฏ๏ผš
        // ๅ›žๆบฏ + ๅ‰ชๆž
        // ็‰นๆฎŠๆƒ…ๅ†ต็‰นๅˆค
        if(k >= n) {
            return res;
        }
        LinkedList<Integer> path = new LinkedList<>();
        mySol(k, n, 1, 0, path);
        return res;
    }

    private void mySol(int k, int target, int index, int sum, LinkedList<Integer> path) {
        // ้€’ๅฝ’็ปˆๆญขๆกไปถ
        if(path.size() == k) {
            if(sum == target) {
                res.add(new LinkedList<>(path));
            }
            return;
        }
        if(index > 9 || sum >= target) {
            return;
        }
        // size() < k
        for(int i = index; i <= 10 - k + path.size(); i ++) {
            path.addLast(i);
            mySol(k, target, i + 1, sum + i, path);
            path.removeLast();
        }
    }
}

่พ“ๅ‡บ

img_3.png

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