-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.php
41 lines (34 loc) · 1.04 KB
/
Solution.php
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
class Solution {
/**
* @param string $digits
* @return string[]
*/
function letterCombinations($digits) {
$digitMap = [
'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'],
];
$combinations = [];
$this->backtrack($digits, '', 0, $digitMap, $combinations);
return $combinations;
}
function backtrack($digits, $current, $index, $digitMap, &$combinations) {
if ($index === strlen($digits)) {
if ($current !== '') {
$combinations[] = $current;
}
return;
}
$digit = $digits[$index];
$letters = $digitMap[$digit];
foreach ($letters as $letter) {
$this->backtrack($digits, $current . $letter, $index + 1, $digitMap, $combinations);
}
}
}