216. 组合总和 III

链接 (opens new window) 20240214234933_image.png

class Solution {

    /**
     * @param  Integer  $k
     * @param  Integer  $n
     * @return Integer[][]
     */
    function combinationSum3($k, $n) {
        $result = [];
        $this->dfs($k, $n, 1, [], $result);
        return $result;
    }

    function dfs($k, $target, $start, $path, &$result) {
        if ($k == 0 && $target == 0) {
            $result[] = $path;
            return;
        }
        if ($target < 0) {
            return;
        }
        for ($i = $start; $i < 10; $i++) {
            $path[] = $i;
            //printf("i:%d, k:%d, t:%d, path:%s\n", $i, $k, $target, implode(" ", $path));
            $this->dfs($k - 1, $target - $i, $i + 1, $path, $result);
            array_pop($path);
        }
    }
}

copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30