티스토리 뷰
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
[leetcode][C++][Java] letter combinations of a phone number
C++
class Solution {
public:
string arr[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
void dfs(int n, string digits, string s, vector<string> &ret) {
if (n == digits.size()) {
ret.push_back(s);
return;
}
int arri = digits[n] - '0';
for (char c : arr[arri]) {
s.push_back(c);
dfs(n + 1, digits, s, ret);
s.pop_back();
}
}
vector<string> letterCombinations(string digits) {
vector<string> ret;
if (!digits.empty())
dfs(0, digits, "", ret);
return ret;
}
};
Java
class Solution {
private String[] phone = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public void dfs(char[] arr, int n, String s, List<String> ans) {
if (n == arr.length) {
ans.add(s);
return;
}
for (char c : phone[arr[n] - '0'].toCharArray()) {
s += c;
dfs(arr, n + 1, s, ans);
s = s.substring(0, s.length() - 1);
}
}
public List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<>();
if(digits.length() == 0) return ans;
char[] arr = digits.toCharArray();
dfs(arr, 0, "", ans);
return ans;
}
}
'Problem Solving' 카테고리의 다른 글
[leetcode][C++] sort colors (0) | 2021.10.15 |
---|---|
[leetcode][C++][Java] jump game (0) | 2021.10.15 |
[leetcode][C++] search in rotated sorted array (0) | 2021.10.06 |
[leetcode][C++] generate parentheses (0) | 2021.10.05 |
[프로그래머스][C++] 모음사전 (0) | 2021.10.04 |
댓글