From 76aa7c95fbd06310d1e41288c0182f2bc7b023b2 Mon Sep 17 00:00:00 2001
From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com>
Date: Mon, 14 Apr 2025 20:50:07 +0530
Subject: [PATCH 1/6] Create 17. Letter Combinations of a Phone Number.py
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com>
Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
---
.../17. Letter Combinations of a Phone Number.py | 10 ++++++++++
1 file changed, 10 insertions(+)
create mode 100644 Solution/17. Letter Combinations of a Phone Number/17. Letter Combinations of a Phone Number.py
diff --git a/Solution/17. Letter Combinations of a Phone Number/17. Letter Combinations of a Phone Number.py b/Solution/17. Letter Combinations of a Phone Number/17. Letter Combinations of a Phone Number.py
new file mode 100644
index 0000000..2136237
--- /dev/null
+++ b/Solution/17. Letter Combinations of a Phone Number/17. Letter Combinations of a Phone Number.py
@@ -0,0 +1,10 @@
+class Solution:
+ def letterCombinations(self, digits: str) -> List[str]:
+ if not digits:
+ return []
+ d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
+ ans = [""]
+ for i in digits:
+ s = d[int(i) - 2]
+ ans = [a + b for a in ans for b in s]
+ return ans
\ No newline at end of file
From 716d3e39a7a867a8e3e2ce325d5931a98b9d50a7 Mon Sep 17 00:00:00 2001
From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com>
Date: Mon, 14 Apr 2025 20:51:20 +0530
Subject: [PATCH 2/6] Create readme.md
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com>
Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
---
.../readme.md | 160 ++++++++++++++++++
1 file changed, 160 insertions(+)
create mode 100644 Solution/17. Letter Combinations of a Phone Number/readme.md
diff --git a/Solution/17. Letter Combinations of a Phone Number/readme.md b/Solution/17. Letter Combinations of a Phone Number/readme.md
new file mode 100644
index 0000000..4d62bb4
--- /dev/null
+++ b/Solution/17. Letter Combinations of a Phone Number/readme.md
@@ -0,0 +1,160 @@
+To create a structured markdown template similar to the one you've shown for the problem "Letter Combinations of a Phone Number" on LeetCode, you can use the following format:
+
+```markdown
+---
+comments: true
+difficulty: Medium
+edit_url: [Your Edit URL Here]
+tags:
+ - Hash Table
+ - String
+ - Backtracking
+---
+
+
+
+# [Problem Title](Problem URL)
+
+[中文文档](Link to Chinese Documentation if available)
+
+## Description
+
+
+
+Description of the problem statement goes here.
+
+### Example 1:
+
+```plaintext
+Input: Example Input
+Output: Example Output
+```
+
+
+
+## Solutions
+
+
+
+### Solution 1: Traversal
+
+Explanation of the traversal solution.
+
+
+
+#### Python
+
+```python
+# Python code snippet
+```
+
+#### Java
+
+```java
+// Java code snippet
+```
+
+#### C++
+
+```cpp
+// C++ code snippet
+```
+
+#### Go
+
+```go
+// Go code snippet
+```
+
+#### TypeScript
+
+```ts
+// TypeScript code snippet
+```
+
+#### Rust
+
+```rust
+// Rust code snippet
+```
+
+#### JavaScript
+
+```js
+// JavaScript code snippet
+```
+
+#### C#
+
+```cs
+// C# code snippet
+```
+
+
+
+
+
+
+
+### Solution 2: DFS
+
+Explanation of the DFS solution.
+
+
+
+#### Python
+
+```python
+# Python code snippet for DFS
+```
+
+#### Java
+
+```java
+// Java code snippet for DFS
+```
+
+#### C++
+
+```cpp
+// C++ code snippet for DFS
+```
+
+#### Go
+
+```go
+// Go code snippet for DFS
+```
+
+#### TypeScript
+
+```ts
+// TypeScript code snippet for DFS
+```
+
+#### Rust
+
+```rust
+// Rust code snippet for DFS
+```
+
+#### JavaScript
+
+```js
+// JavaScript code snippet for DFS
+```
+
+#### C#
+
+```cs
+// C# code snippet for DFS
+```
+
+
+
+
+
+
+```
+
+Replace placeholders such as `[Problem Title](Problem URL)`, `Description of the problem statement goes here.`, and code snippets with actual content. This structure allows for clear organization of problem descriptions, examples, solutions, and code snippets across multiple programming languages. Adjust the tags, difficulty, and edit URL as per your specific needs.
\ No newline at end of file
From a91890795f8ad3e80c50cabf20fdd5368c16d7ec Mon Sep 17 00:00:00 2001
From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com>
Date: Mon, 14 Apr 2025 20:51:41 +0530
Subject: [PATCH 3/6] Update readme.md
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com>
Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
---
Solution/17. Letter Combinations of a Phone Number/readme.md | 3 ---
1 file changed, 3 deletions(-)
diff --git a/Solution/17. Letter Combinations of a Phone Number/readme.md b/Solution/17. Letter Combinations of a Phone Number/readme.md
index 4d62bb4..a953a10 100644
--- a/Solution/17. Letter Combinations of a Phone Number/readme.md
+++ b/Solution/17. Letter Combinations of a Phone Number/readme.md
@@ -155,6 +155,3 @@ Explanation of the DFS solution.
-```
-
-Replace placeholders such as `[Problem Title](Problem URL)`, `Description of the problem statement goes here.`, and code snippets with actual content. This structure allows for clear organization of problem descriptions, examples, solutions, and code snippets across multiple programming languages. Adjust the tags, difficulty, and edit URL as per your specific needs.
\ No newline at end of file
From 3ba4d138e83af43d4833616aaa50f4815ac07985 Mon Sep 17 00:00:00 2001
From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com>
Date: Mon, 14 Apr 2025 20:53:36 +0530
Subject: [PATCH 4/6] Update readme.md
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com>
Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
---
.../readme.md | 467 ++++++++++++++++--
1 file changed, 434 insertions(+), 33 deletions(-)
diff --git a/Solution/17. Letter Combinations of a Phone Number/readme.md b/Solution/17. Letter Combinations of a Phone Number/readme.md
index a953a10..21635f8 100644
--- a/Solution/17. Letter Combinations of a Phone Number/readme.md
+++ b/Solution/17. Letter Combinations of a Phone Number/readme.md
@@ -1,10 +1,7 @@
-To create a structured markdown template similar to the one you've shown for the problem "Letter Combinations of a Phone Number" on LeetCode, you can use the following format:
-
-```markdown
---
comments: true
difficulty: Medium
-edit_url: [Your Edit URL Here]
+edit_url: https://github.com/doocs/leetcode/edit/main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/README_EN.md
tags:
- Hash Table
- String
@@ -13,22 +10,47 @@ tags:
-# [Problem Title](Problem URL)
+# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number)
-[中文文档](Link to Chinese Documentation if available)
+[中文文档](/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/README.md)
## Description
-Description of the problem statement goes here.
+
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.
-### Example 1:
+A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
+
+
+Example 1:
-```plaintext
-Input: Example Input
-Output: Example Output
-```
+
+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'].
+
@@ -38,56 +60,203 @@ Output: Example Output
### Solution 1: Traversal
-Explanation of the traversal solution.
+First, we use an array or hash table to store the letters corresponding to each digit. Then we traverse each digit, combine its corresponding letters with the previous results to get the new results.
+
+The time complexity is $O(4^n)$, and the space complexity is $O(4^n)$. Here, $n$ is the length of the input digits.
-#### Python
+#### Python3
```python
-# Python code snippet
+class Solution:
+ def letterCombinations(self, digits: str) -> List[str]:
+ if not digits:
+ return []
+ d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
+ ans = [""]
+ for i in digits:
+ s = d[int(i) - 2]
+ ans = [a + b for a in ans for b in s]
+ return ans
```
#### Java
```java
-// Java code snippet
+class Solution {
+ public List letterCombinations(String digits) {
+ List ans = new ArrayList<>();
+ if (digits.length() == 0) {
+ return ans;
+ }
+ ans.add("");
+ String[] d = new String[] {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+ for (char i : digits.toCharArray()) {
+ String s = d[i - '2'];
+ List t = new ArrayList<>();
+ for (String a : ans) {
+ for (String b : s.split("")) {
+ t.add(a + b);
+ }
+ }
+ ans = t;
+ }
+ return ans;
+ }
+}
```
#### C++
```cpp
-// C++ code snippet
+class Solution {
+public:
+ vector letterCombinations(string digits) {
+ if (digits.empty()) {
+ return {};
+ }
+ vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+ vector ans = {""};
+ for (auto& i : digits) {
+ string s = d[i - '2'];
+ vector t;
+ for (auto& a : ans) {
+ for (auto& b : s) {
+ t.push_back(a + b);
+ }
+ }
+ ans = move(t);
+ }
+ return ans;
+ }
+};
```
#### Go
```go
-// Go code snippet
+func letterCombinations(digits string) []string {
+ ans := []string{}
+ if len(digits) == 0 {
+ return ans
+ }
+ ans = append(ans, "")
+ d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
+ for _, i := range digits {
+ s := d[i-'2']
+ t := []string{}
+ for _, a := range ans {
+ for _, b := range s {
+ t = append(t, a+string(b))
+ }
+ }
+ ans = t
+ }
+ return ans
+}
```
#### TypeScript
```ts
-// TypeScript code snippet
+function letterCombinations(digits: string): string[] {
+ if (digits.length === 0) {
+ return [];
+ }
+ const ans: string[] = [''];
+ const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
+ for (const i of digits) {
+ const s = d[+i - 2];
+ const t: string[] = [];
+ for (const a of ans) {
+ for (const b of s) {
+ t.push(a + b);
+ }
+ }
+ ans.splice(0, ans.length, ...t);
+ }
+ return ans;
+}
```
#### Rust
```rust
-// Rust code snippet
+impl Solution {
+ pub fn letter_combinations(digits: String) -> Vec {
+ let mut ans: Vec = Vec::new();
+ if digits.is_empty() {
+ return ans;
+ }
+ ans.push("".to_string());
+ let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
+ for i in digits.chars() {
+ let s = &d[((i as u8) - b'2') as usize];
+ let mut t: Vec = Vec::new();
+ for a in &ans {
+ for b in s.chars() {
+ t.push(format!("{}{}", a, b));
+ }
+ }
+ ans = t;
+ }
+ ans
+ }
+}
```
#### JavaScript
```js
-// JavaScript code snippet
+/**
+ * @param {string} digits
+ * @return {string[]}
+ */
+var letterCombinations = function (digits) {
+ if (digits.length === 0) {
+ return [];
+ }
+ const ans = [''];
+ const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
+ for (const i of digits) {
+ const s = d[+i - 2];
+ const t = [];
+ for (const a of ans) {
+ for (const b of s) {
+ t.push(a + b);
+ }
+ }
+ ans.splice(0, ans.length, ...t);
+ }
+ return ans;
+};
```
#### C#
```cs
-// C# code snippet
+public class Solution {
+ public IList LetterCombinations(string digits) {
+ var ans = new List();
+ if (digits.Length == 0) {
+ return ans;
+ }
+ ans.Add("");
+ string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+ foreach (char i in digits) {
+ string s = d[i - '2'];
+ var t = new List();
+ foreach (string a in ans) {
+ foreach (char b in s) {
+ t.Add(a + b);
+ }
+ }
+ ans = t;
+ }
+ return ans;
+ }
+}
```
@@ -98,60 +267,292 @@ Explanation of the traversal solution.
### Solution 2: DFS
-Explanation of the DFS solution.
+We can use the method of depth-first search to enumerate all possible letter combinations. Suppose that a part of the letter combination has been generated, but some digits have not been exhausted. At this time, we take out the letters corresponding to the next digit, and then enumerate each letter corresponding to this digit one by one, add them to the letter combination that has been generated before, to form all possible combinations.
+
+The time complexity is $O(4^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the input digits.
-#### Python
+#### Python3
```python
-# Python code snippet for DFS
+class Solution:
+ def letterCombinations(self, digits: str) -> List[str]:
+ def dfs(i: int):
+ if i >= len(digits):
+ ans.append("".join(t))
+ return
+ for c in d[int(digits[i]) - 2]:
+ t.append(c)
+ dfs(i + 1)
+ t.pop()
+
+ if not digits:
+ return []
+ d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
+ ans = []
+ t = []
+ dfs(0)
+ return ans
```
#### Java
```java
-// Java code snippet for DFS
+class Solution {
+ private final String[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+ private String digits;
+ private List ans = new ArrayList<>();
+ private StringBuilder t = new StringBuilder();
+
+ public List letterCombinations(String digits) {
+ if (digits.length() == 0) {
+ return ans;
+ }
+ this.digits = digits;
+ dfs(0);
+ return ans;
+ }
+
+ private void dfs(int i) {
+ if (i >= digits.length()) {
+ ans.add(t.toString());
+ return;
+ }
+ String s = d[digits.charAt(i) - '2'];
+ for (char c : s.toCharArray()) {
+ t.append(c);
+ dfs(i + 1);
+ t.deleteCharAt(t.length() - 1);
+ }
+ }
+}
```
#### C++
```cpp
-// C++ code snippet for DFS
+class Solution {
+public:
+ vector letterCombinations(string digits) {
+ if (digits.empty()) {
+ return {};
+ }
+ vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+ vector ans;
+ string t;
+ function dfs = [&](int i) {
+ if (i >= digits.size()) {
+ ans.push_back(t);
+ return;
+ }
+ for (auto& c : d[digits[i] - '2']) {
+ t.push_back(c);
+ dfs(i + 1);
+ t.pop_back();
+ }
+ };
+ dfs(0);
+ return ans;
+ }
+};
```
#### Go
```go
-// Go code snippet for DFS
+func letterCombinations(digits string) (ans []string) {
+ d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
+ t := []rune{}
+ var dfs func(int)
+ dfs = func(i int) {
+ if i >= len(digits) {
+ ans = append(ans, string(t))
+ return
+ }
+ for _, c := range d[digits[i]-'2'] {
+ t = append(t, c)
+ dfs(i + 1)
+ t = t[:len(t)-1]
+ }
+ }
+ if len(digits) == 0 {
+ return
+ }
+ dfs(0)
+ return
+}
```
#### TypeScript
```ts
-// TypeScript code snippet for DFS
+function letterCombinations(digits: string): string[] {
+ if (digits.length === 0) {
+ return [];
+ }
+ const ans: string[] = [];
+ const t: string[] = [];
+ const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
+ const dfs = (i: number) => {
+ if (i >= digits.length) {
+ ans.push(t.join(''));
+ return;
+ }
+ const s = d[+digits[i] - 2];
+ for (const c of s) {
+ t.push(c);
+ dfs(i + 1);
+ t.pop();
+ }
+ };
+ dfs(0);
+ return ans;
+}
```
#### Rust
```rust
-// Rust code snippet for DFS
+impl Solution {
+ pub fn letter_combinations(digits: String) -> Vec {
+ let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
+ let mut ans = Vec::new();
+ let mut t = String::new();
+ if digits.is_empty() {
+ return ans;
+ }
+ Solution::dfs(&digits, &d, &mut t, &mut ans, 0);
+ ans
+ }
+
+ fn dfs(digits: &String, d: &[&str; 8], t: &mut String, ans: &mut Vec, i: usize) {
+ if i >= digits.len() {
+ ans.push(t.clone());
+ return;
+ }
+ let s = d[((digits.chars().nth(i).unwrap() as u8) - b'2') as usize];
+ for c in s.chars() {
+ t.push(c);
+ Solution::dfs(digits, d, t, ans, i + 1);
+ t.pop();
+ }
+ }
+}
```
#### JavaScript
```js
-// JavaScript code snippet for DFS
+/**
+ * @param {string} digits
+ * @return {string[]}
+ */
+var letterCombinations = function (digits) {
+ if (digits.length === 0) {
+ return [];
+ }
+ const ans = [];
+ const t = [];
+ const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
+ const dfs = i => {
+ if (i >= digits.length) {
+ ans.push(t.join(''));
+ return;
+ }
+ const s = d[+digits[i] - 2];
+ for (const c of s) {
+ t.push(c);
+ dfs(i + 1);
+ t.pop();
+ }
+ };
+ dfs(0);
+ return ans;
+};
```
#### C#
```cs
-// C# code snippet for DFS
+public class Solution {
+ private readonly string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+ private string digits;
+ private List ans = new List();
+ private System.Text.StringBuilder t = new System.Text.StringBuilder();
+
+ public IList LetterCombinations(string digits) {
+ if (digits.Length == 0) {
+ return ans;
+ }
+ this.digits = digits;
+ Dfs(0);
+ return ans;
+ }
+
+ private void Dfs(int i) {
+ if (i >= digits.Length) {
+ ans.Add(t.ToString());
+ return;
+ }
+ string s = d[digits[i] - '2'];
+ foreach (char c in s) {
+ t.Append(c);
+ Dfs(i + 1);
+ t.Remove(t.Length - 1, 1);
+ }
+ }
+}
+```
+
+#### PHP
+
+```php
+class Solution {
+ /**
+ * @param string $digits
+ * @return string[]
+ */
+
+ function letterCombinations($digits) {
+ $digitMap = [
+ '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'],
+ ];
+
+ $combinations = [];
+
+ backtrack($digits, '', 0, $digitMap, $combinations);
+
+ return $combinations;
+ }
+
+ function backtrack($digits, $current, $index, $digitMap, &$combinations) {
+ if ($index === strlen($digits)) {
+ if ($current !== '') {
+ $combinations[] = $current;
+ }
+ return;
+ }
+
+ $digit = $digits[$index];
+ $letters = $digitMap[$digit];
+
+ foreach ($letters as $letter) {
+ backtrack($digits, $current . $letter, $index + 1, $digitMap, $combinations);
+ }
+ }
+}
```
-
+
\ No newline at end of file
From 735c974676a049a00b9235ecce8c805d4f1451e2 Mon Sep 17 00:00:00 2001
From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com>
Date: Mon, 14 Apr 2025 20:54:32 +0530
Subject: [PATCH 5/6] Update readme.md
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com>
Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
---
.../readme.md | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/Solution/17. Letter Combinations of a Phone Number/readme.md b/Solution/17. Letter Combinations of a Phone Number/readme.md
index 21635f8..2eb92b6 100644
--- a/Solution/17. Letter Combinations of a Phone Number/readme.md
+++ b/Solution/17. Letter Combinations of a Phone Number/readme.md
@@ -1,19 +1,18 @@
+
+
+
+
+# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number)
+
---
comments: true
difficulty: Medium
-edit_url: https://github.com/doocs/leetcode/edit/main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/README_EN.md
tags:
- Hash Table
- String
- Backtracking
---
-
-
-# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number)
-
-[中文文档](/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/README.md)
-
## Description
From 02e9a62a3b78787a7db506678e373891614d6a7d Mon Sep 17 00:00:00 2001
From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com>
Date: Mon, 14 Apr 2025 20:55:13 +0530
Subject: [PATCH 6/6] Update readme.md
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com>
Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
---
.../17. Letter Combinations of a Phone Number/readme.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/Solution/17. Letter Combinations of a Phone Number/readme.md b/Solution/17. Letter Combinations of a Phone Number/readme.md
index 2eb92b6..ee14e79 100644
--- a/Solution/17. Letter Combinations of a Phone Number/readme.md
+++ b/Solution/17. Letter Combinations of a Phone Number/readme.md
@@ -5,9 +5,9 @@
# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number)
---
-comments: true
-difficulty: Medium
-tags:
+- **comments**: true
+- **difficulty**: Medium
+- **tags**:
- Hash Table
- String
- Backtracking