https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Letter Combinations of a Phone Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
간단한 조합문제이다.
2~9까지 각 해당하는 문자들이 존재한다.
2~9 인덱스를 활용하기위해 미리 문자배열들을 만들어두었다.
각 인덱스를 통해서 재귀함수로 조합을 뽑아낸다.
class Solution {
var list = [[], [], ["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"]]
var answer = [String]()
var stack = ""
func letterCombinations(_ digits: String) -> [String] {
dfs(0, 0, digits.count, digits.map{Int(String($0))!})
return answer
}
func dfs(_ count: Int, _ idx: Int, _ mx: Int, _ digits: [Int] ) {
if count == mx {
if stack.isEmpty { return }
answer.append(stack)
return
}
for i in list[digits[idx]] {
stack.append(i)
dfs(count+1, idx+1, mx, digits)
stack.removeLast()
}
}
}
'코딩테스트' 카테고리의 다른 글
백준 1508 - 레이스 - swift (0) | 2021.06.23 |
---|---|
백준 1459 - 걷기 - swift (0) | 2021.06.23 |
프로그래머스 - [1차] 비밀지도 - swift (0) | 2021.06.22 |
백준 15961 - 회전초밥 - swift (0) | 2021.06.22 |
LeetCode - 20. Valid Parentheses - swift (0) | 2021.06.16 |