-
[LeetCode] 17. Letter Combinations of a Phone Number / Swift프로그래밍/코딩테스트 2021. 7. 6. 15:24
[문제 보기]
더보기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 digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = "" Output: []
Example 3:
Input: digits = "2" Output: ["a","b","c"]
Constraints:
- 0 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
n개의 집합들에서 각각 1개씩 뽑는 모든 조합의 경우의 수를 구하는 문제였다.
이 부분은 전에도 한번 고민하고 정리해본 거라서 생각보다 쉽게 구현할 수 있었다.
해당 내용 정리한 글:
제출 코드:
class Solution { func letterCombinations(_ digits: String) -> [String] { let input = digits.map{Int(String($0))!} let container = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] var candidates = [[String]]() for element in input { candidates.append(container[element - 2].map{String($0)}) } if candidates.count < 1 { return [] } var ans = [String]() var index = [Int](repeating: 0, count: candidates.count) while index[0] < candidates[0].count { var str = "" for (i, element) in index.enumerated() { str.append(candidates[i][element]) } ans.append(str) var cur = index.count - 1 index[cur] += 1 while cur > 0 { if index[cur] >= candidates[cur].count { index[cur] = 0 index[cur - 1] += 1 cur -= 1 } else { break } } } return ans } }
반응형'프로그래밍 > 코딩테스트' 카테고리의 다른 글
[LeetCode] 19. Remove Nth Node From End of List / Swift (0) 2021.07.06 [LeetCode] 15. 3Sum / Swift (0) 2021.07.02 [LeetCode] 11. Container With Most Water / Swift (0) 2021.07.01 [LeetCode] 5. Longest Palindromic Substring / Swift (0) 2021.07.01 [LeetCode] 3. Longest Substring Without Repeating Characters / Swift (0) 2021.06.30