runtime 0 ms, beats 100% of cpp submissions
O(k^n) solution with explanation

tags: recursion

Letter Combinations of a Phone Number

๐Ÿ“– description

็ตฆๅฎšไธ€ๅ€‹ๆŒ‰้ต็š„่ผธๅ…ฅๅญ—ไธฒ๏ผŒๆžš่ˆ‰ๅ‡บๆ‰€ๆœ‰ๅฏ่ƒฝ็š„่กจ็คบๆ„ๆ€

2 -> abc
3 -> def
4 -> ghi
5 -> jkl
6 -> mno
7 -> pqrs
8 -> tuv
9 -> wxyz
ex.
    digits = "23"
    output = ["ad","ae","af","bd","be","bf","cd","ce","cf"]

๐Ÿง  solution

ไธ€ๅ€‹็ถ“ๅ…ธ็š„ๅ…จๆŽ’ๅˆ—้กŒ็›ฎ๏ผŒๅœจๆฏๅ€‹้šŽๆฎต้ƒฝๆžš็•ถๅ‰ index ็š„ๆ‰€ๆœ‰ๅฏ่ƒฝ่กจ็คบๆ–นๅผ

โณ time complexity

่ฆๆžš่ˆ‰ๆฏๅ€‹ index ็š„ๆ‰€ๆœ‰ๅฏ่ƒฝๅญ—ๅ…ƒ๏ผŒๆฏๅ€‹ๅญ—ๅ…ƒๆœ‰ 3 ๆˆ– 4 ๅ€‹ๅฏ่ƒฝ๏ผŒๅญ—ไธฒ้•ทๅบฆ็‚บ n ๏ผŒ ๆ™‚้–“่ค‡้›œๅบฆ็‚บ O(k^n)
็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(k^n)

๐Ÿ“ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<string> phone = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> ans;
void re(string& d,string& now,int ind){
if(ind>=d.size()){
ans.emplace_back(now);
return;
}
for(int i=0;i<phone[d[ind]-'0'].size();i++){
now+=phone[d[ind]-'0'][i];
re(d,now,ind+1);
now.pop_back();
}
}
vector<string> letterCombinations(string& digits) {
if(digits.size()==0) return {};
ans.clear();
string now;
re(digits,now,0);
return ans;
}
};