Commit 4b9c663
committed
17. Letter Combinations of a Phone Number
```Solution.c /** * Note: The returned array must be malloced, assume caller calls free(). */ const char* mapping[] = { "", // 0 "", // 1 "abc", // 2 "def", // 3 "ghi", // 4 "jkl", // 5 "mno", // 6 "pqrs", // 7 "tuv", // 8 "wxyz" // 9 }; void backtrack(char* digits, int index, char* current, char** result, int* count) { if (digits[index] == '\0') { result[*count] = strdup(current); (*count)++; return; } int digit = digits[index] - '0'; if (digit < 2 || digit > 9) { backtrack(digits, index + 1, current, result, count); return; } const char* letters = mapping[digit]; for (int i = 0; letters[i] != '\0'; i++) { current[index] = letters[i]; backtrack(digits, index + 1, current, result, count); } } char** letterCombinations(char* digits, int* returnSize) { if (!digits || digits[0] == '\0') { *returnSize = 0; return NULL; } int len = strlen(digits); int maxSize = 1; for (int i = 0; i < len; i++) { int digit = digits[i] - '0'; if (digit < 2 || digit > 9) { *returnSize = 0; return NULL; } int lettersCount = strlen(mapping[digit]); maxSize *= lettersCount; } char** result = (char**)malloc(maxSize * sizeof(char*)); char* current = (char*)malloc((len + 1) * sizeof(char)); current[len] = '\0'; int count = 0; backtrack(digits, 0, current, result, &count); free(current); *returnSize = count; return result; } ``` ```Solution.cpp class Solution { public: vector<string> letterCombinations(string digits) { if (digits.empty()) return {}; vector<string> mapping = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> result; function<void(int, string)> backtrack = [&](int idx, string curr) { if (idx == digits.size()) { result.push_back(curr); return; } for (char c : mapping[digits[idx] - '0']) { backtrack(idx + 1, curr + c); } }; backtrack(0, ""); return result; } }; ``` ```Solution.cs public class Solution { public IList<string> LetterCombinations(string digits) { var result = new List<string>(); if (string.IsNullOrEmpty(digits)) return result; string[] mapping = new string[] { "", // 0 "", // 1 "abc", // 2 "def", // 3 "ghi", // 4 "jkl", // 5 "mno", // 6 "pqrs",// 7 "tuv", // 8 "wxyz" // 9 }; Backtrack(digits, mapping, 0, "", result); return result; } private void Backtrack(string digits, string[] mapping, int index, string current, List<string> result) { if (index == digits.Length) { result.Add(current); return; } string letters = mapping[digits[index] - '0']; foreach (char c in letters) { Backtrack(digits, mapping, index + 1, current + c, result); } } } ``` ```Solution.dart class Solution { List<String> letterCombinations(String digits) { if (digits.isEmpty) return []; Map<String, String> phone = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', }; List<String> result = []; void backtrack(String combination, int next) { if (next == digits.length) { result.add(combination); return; } String letters = phone[digits[next]] ?? ''; for (int i = 0; i < letters.length; i++) { backtrack(combination + letters[i], next + 1); } } backtrack('', 0); return result; } } ``` ```Solution.erl -spec three_sum_closest(Nums :: [integer()], Target :: integer()) -> integer(). -spec letter_combinations(Digits :: unicode:unicode_binary()) -> [unicode:unicode_binary()]. letter_combinations(Digits) when Digits == <<>> -> []; letter_combinations(Digits) -> Map = #{ <<"2">> => [<<"a">>, <<"b">>, <<"c">>], <<"3">> => [<<"d">>, <<"e">>, <<"f">>], <<"4">> => [<<"g">>, <<"h">>, <<"i">>], <<"5">> => [<<"j">>, <<"k">>, <<"l">>], <<"6">> => [<<"m">>, <<"n">>, <<"o">>], <<"7">> => [<<"p">>, <<"q">>, <<"r">>, <<"s">>], <<"8">> => [<<"t">>, <<"u">>, <<"v">>], <<"9">> => [<<"w">>, <<"x">>, <<"y">>, <<"z">>] }, letter_combinations(Digits, Map). letter_combinations(Digits, Map) -> DigitsList = unicode:characters_to_list(Digits), LettersList = [maps:get(<<D>>, Map, []) || D <- DigitsList], combine(LettersList). combine([]) -> []; combine([H]) -> H; combine([H|T]) -> [<<A/binary, B/binary>> || A <- H, B <- combine(T)]. ``` ```Solution.ex defmodule Solution do @SPEC letter_combinations(digits :: String.t) :: [String.t] def letter_combinations("") do [] end def letter_combinations(digits) do mapping = %{ "2" => ["a", "b", "c"], "3" => ["d", "e", "f"], "4" => ["g", "h", "i"], "5" => ["j", "k", "l"], "6" => ["m", "n", "o"], "7" => ["p", "q", "r", "s"], "8" => ["t", "u", "v"], "9" => ["w", "x", "y", "z"] } digits |> String.graphemes() |> Enum.map(&Map.get(mapping, &1, [])) |> Enum.reduce([""], fn letters, acc -> for prefix <- acc, letter <- letters, do: prefix <> letter end) end end ``` ```Solution.go func letterCombinations(digits string) []string { if len(digits) == 0 { return []string{} } mapping := map[byte]string{ '2': "abc", '3': "def", '4': "ghi", '5': "jkl", '6': "mno", '7': "pqrs", '8': "tuv", '9': "wxyz", } var res []string var backtrack func(index int, path string) backtrack = func(index int, path string) { if index == len(digits) { res = append(res, path) return } letters := mapping[digits[index]] for i := 0; i < len(letters); i++ { backtrack(index+1, path+string(letters[i])) } } backtrack(0, "") return res } ``` ```Solution.java class Solution { public List<String> letterCombinations(String digits) { if (digits == null || digits.length() == 0) return new ArrayList<>(); String[] mapping = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; List<String> result = new ArrayList<>(); backtrack(result, digits, mapping, 0, new StringBuilder()); return result; } private void backtrack(List<String> result, String digits, String[] mapping, int index, StringBuilder current) { if (index == digits.length()) { result.add(current.toString()); return; } String letters = mapping[digits.charAt(index) - '0']; for (char c : letters.toCharArray()) { current.append(c); backtrack(result, digits, mapping, index + 1, current); current.deleteCharAt(current.length() - 1); } } } ``` ```Solution.js /** * @param {string} digits * @return {string[]} */ var letterCombinations = function(digits) { if (!digits || digits.length === 0) return []; const map = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' }; const result = []; function backtrack(index, path) { if (index === digits.length) { result.push(path); return; } for (const char of map[digits[index]]) { backtrack(index + 1, path + char); } } backtrack(0, ''); return result; }; ``` ```Solution.kt class Solution { fun letterCombinations(digits: String): List<String> { if (digits.isEmpty()) return emptyList() val map = mapOf( '2' to "abc", '3' to "def", '4' to "ghi", '5' to "jkl", '6' to "mno", '7' to "pqrs", '8' to "tuv", '9' to "wxyz" ) val result = mutableListOf<String>() fun backtrack(index: Int, path: String) { if (index == digits.length) { result.add(path) return } for (c in map[digits[index]] ?: "") { backtrack(index + 1, path + c) } } backtrack(0, "") return result } } ``` ```Solution.php class Solution { /** * @param String $digits * @return String[] */ function letterCombinations($digits) { $map = [ '2' => ['a', 'b', 'c'], '3' => ['d', 'e', 'f'], '4' => ['g', 'h', 'i'], '5' => ['j', 'k', 'l'], '6' => ['m', 'n', 'o'], '7' => ['p', 'q', 'r', 's'], '8' => ['t', 'u', 'v'], '9' => ['w', 'x', 'y', 'z'] ]; if ($digits === "") return []; $result = ['']; for ($i = 0; $i < strlen($digits); $i++) { $letters = $map[$digits[$i]] ?? []; $temp = []; foreach ($result as $comb) { foreach ($letters as $letter) { $temp[] = $comb . $letter; } } $result = $temp; } return $result; } } ``` ```Solution.py class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] phone = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" } res = [] def backtrack(index, path): if index == len(digits): res.append(path) return for char in phone[digits[index]]: backtrack(index + 1, path + char) backtrack(0, "") return res ``` ```Solution.rb # @param {String} digits # @return {String[]} def letter_combinations(digits) return [] if digits.empty? phone = { '2' => %w[a b c], '3' => %w[d e f], '4' => %w[g h i], '5' => %w[j k l], '6' => %w[m n o], '7' => %w[p q r s], '8' => %w[t u v], '9' => %w[w x y z] } result = [''] digits.each_char do |digit| result = result.flat_map { |prefix| phone[digit].map { |char| prefix + char } } end result end ``` ```Solution.rkt (define/contract (letter-combinations digits) (-> string? (listof string?)) (define digit-map (hash "2" '("a" "b" "c") "3" '("d" "e" "f") "4" '("g" "h" "i") "5" '("j" "k" "l") "6" '("m" "n" "o") "7" '("p" "q" "r" "s") "8" '("t" "u" "v") "9" '("w" "x" "y" "z"))) (define (combine lst1 lst2) (if (null? lst1) lst2 (apply append (map (λ (x) (map (λ (y) (string-append x y)) lst2)) lst1)))) (if (string=? digits "") '() (let loop ((idx 0) (result '(""))) (if (= idx (string-length digits)) result (let* ((d (substring digits idx (+ idx 1))) (letters (hash-ref digit-map d '()))) (loop (+ idx 1) (combine result letters))))))) ``` ```Solution.rs impl Solution { pub fn letter_combinations(digits: String) -> Vec<String> { if digits.is_empty() { return Vec::new(); } let map = vec![ "", // 0 "", // 1 "abc", // 2 "def", // 3 "ghi", // 4 "jkl", // 5 "mno", // 6 "pqrs",// 7 "tuv", // 8 "wxyz" // 9 ]; let mut res = vec![String::new()]; for d in digits.chars() { let idx = d.to_digit(10).unwrap() as usize; let letters = map[idx]; let mut tmp = Vec::new(); for prefix in &res { for ch in letters.chars() { let mut new_str = prefix.clone(); new_str.push(ch); tmp.push(new_str); } } res = tmp; } res } } ``` ```Solution.scala object Solution { def letterCombinations(digits: String): List[String] = { val digitToLetters = Map( '2' -> "abc", '3' -> "def", '4' -> "ghi", '5' -> "jkl", '6' -> "mno", '7' -> "pqrs", '8' -> "tuv", '9' -> "wxyz" ) if (digits.isEmpty) return List() digits.foldLeft(List("")) { (acc, digit) => for { combination <- acc letter <- digitToLetters.getOrElse(digit, "") } yield combination + letter } } } ``` ```Solution.swift class Solution { func letterCombinations(_ digits: String) -> [String] { if digits.isEmpty { return [] } let mapping: [Character: [String]] = [ "2": ["a", "b", "c"], "3": ["d", "e", "f"], "4": ["g", "h", "i"], "5": ["j", "k", "l"], "6": ["m", "n", "o"], "7": ["p", "q", "r", "s"], "8": ["t", "u", "v"], "9": ["w", "x", "y", "z"] ] var result: [String] = [""] for digit in digits { guard let letters = mapping[digit] else { continue } var temp: [String] = [] for prefix in result { for letter in letters { temp.append(prefix + letter) } } result = temp } return result } } ``` ```Solution.ts function letterCombinations(digits: string): string[] { if (!digits) return []; const map: { [key: string]: string } = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" }; const result: string[] = []; const backtrack = (comb: string, nextDigits: string) => { if (nextDigits.length === 0) { result.push(comb); return; } for (const letter of map[nextDigits[0]]) { backtrack(comb + letter, nextDigits.slice(1)); } }; backtrack("", digits); return result; } ```1 parent 8440f60 commit 4b9c663
File tree
20 files changed
+514
-0
lines changed- res/ino
- sol/solution/0001-0100/0017
20 files changed
+514
-0
lines changedLoading
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
0 commit comments