Algorithm/PTUStudy
15주차. 그래프(전화번호 문자 조합)
지구우중
2023. 5. 12. 14:27
33. 전화번호 문자 조합
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Letter Combinations of a Phone Number - LeetCode
Can you solve this real interview question? Letter Combinations of a Phone Number - Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of d
leetcode.com
📌문제
2에서 9까지 숫자가 주어졌을 때 전화번호로 조합 가능한 모든 문자를 출력하라.
- 예제1
📝입력
digits = "23"
💻출력
["ad","ae","af","bd","be","bf","cd","ce","cf"]
📌풀이
5ms, 42.7mb
class Solution {
public List<String> letterCombinations(String digits) {
//int n = 8, m = 4, alpa = 97;
List<String> answer = new ArrayList<>();
if(digits.length() == 0) return answer;
// 97 122
char[][] arr = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},
{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
/*for(int i = 0; i < n; i++){
m = ( alpa == 'p' || alpa == 'w') ? 4 : 3;
for(int j = 0; j < m; j++){
arr[i][j] = (char)alpa++;
}
}*/
combination(arr, answer, 0, digits,"");
return answer;
}
public void combination(char[][] arr, List<String> list, int depth, String digits, String result){
if(depth == digits.length()){
list.add(result);
return;
}
char[] first = arr[(digits.charAt(depth)-'0')-2];
for(int i = 0; i < first.length; i++){
//if(first[i] == 0) continue;
combination(arr, list, depth+1, digits, result + first[i]);
}
}
알파벳 배열 일일히 값넣어 만들기 귀찮아서 for문으로 만들어줬었는데(주석처리 부분), 런타임 시간이 똥망으로 나와서 배열에 일일히 넣어주는 것으로 바꿨으나(for문 몇십번 도는데 차이가 있을리가..) 예상대로 런타임 시간이 똥망이라 다음주차에 리팩토링할 예정이다.. 어쨌든 스스로 풀었다는 것에 의의를 두고 다음 주차때 맛깔나게 리팩토링을 해보겠... 크음..