class Solution { public $phone = [ '2' => ['a', 'b', 'c'], '3' => ['d', 'e', 'f'], '4' => ['g', 'h', 'i'], '5' => ['j', 'k', 'l'], '6' => ['m', 'n', 'o'], '7' => ['p', 'q', 'r', 's'], '8' => ['t', 'u', 'v'], '9' => ['w', 'x', 'y', 'z'] ]; public $result = []; /** * @param String $digits * @return String[] */ function letterCombinations($digits) { if(strlen($digits) > 0) { //$this->dfs($digits, 0,""); $this->dfs2($digits, ""); } return $this->result; } function dfs($digits, $level, $path) { if (strlen($digits) == $level) { $this->result[] = $path; return; } for ($i = 0, $iMax = count($this->phone[$digits[$level]]); $i < $iMax; $i++) { $this->dfs($digits, $level + 1,$path.$this->phone[$digits[$level]][$i]); } } function dfs2($digits, $path) { if (strlen($digits) == 0) { $this->result[] = $path; return; } foreach ($this->phone[$digits[0]] as $iValue) { //$path .= $iValue; $this->dfs2(substr($digits, 1), $path . $iValue); //$path = substr($path, 0, -1); } } }
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution { public $result = []; //组合的递归写法 function combination($arr) { $this->dfs($arr, '', 0); return $this->result; } function dfs($arr, $path, $level) { if ($level == count($arr)) { $this->result[] = $path; return; } foreach ($arr[$level] as $num) { $this->dfs($arr, $path.$num, $level + 1); } } } $arr = [['a', 'b', 'c'], ['d', 'e', 'f']]; print_r((new Solution)->combination($arr));
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
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