From dc5539c3f7603b1249fc0cf2ca75a7a11d7db0ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Sun, 16 Dec 2018 23:52:21 +0800 Subject: [PATCH] Create 17. Letter Combinations of a Phone Number.md --- 17. Letter Combinations of a Phone Number.md | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 17. Letter Combinations of a Phone Number.md diff --git a/17. Letter Combinations of a Phone Number.md b/17. Letter Combinations of a Phone Number.md new file mode 100644 index 0000000..fbf662e --- /dev/null +++ b/17. Letter Combinations of a Phone Number.md @@ -0,0 +1,57 @@ +# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) +# 思路 +## 思路一 +举例说明吧。 +1. `digits = "2"`时,结果显然是`res = ["a","b","c"]`; +2. `digits = "23"`时,1中res的每一个字符串后都可以接d、e、f任意一个,所以可以先将1中的res中所有元素复制两遍 +变成["a","b","c","a","b","c","a","b","c"],再在此时res的每一个元素后面合适地接上d、e、f其中一个就变成了 +["ad","bd","cd","ae","be","ce","af","bf","cf"]。 + +由此就可以写出代码了。 +时间复杂度O(n^2),空间复杂度O(1) + +## 思路二 +其实可以将此题看成求解一棵树的所有root(root可以看做是空)到叶子的路径。 +例如当`digits = "23"`时,树应该是这个样子: +``` + root + / | \ + 2: a b c + /|\ /|\ /|\ + 3: def def def +``` +所以就可以用DFS求解这题了。 + + +# C++ +## 思路一 +```C++ +class Solution { +public: + vector letterCombinations(string digits) { + int len = digits.size(); + vectorres; + if(len == 0) return res; + + const vectordigit2char{"","","abc","def","ghi", + "jkl","mno","pqrs","tuv","wxyz"}; + res.push_back(""); + for(int i = 0; i < len; i++){ + int digit = int(digits[i] - '0'); + int curr_res_size = res.size(); + for(int k = 0; k < digit2char[digit].size() - 1; k++) // 将res中所有元素复制几遍 + for(int j = 0; j < curr_res_size; j++) + res.push_back(res[j]); + for(int k = 0; k < digit2char[digit].size(); k++) + for(int j = 0; j < curr_res_size; j++) + res[k * curr_res_size + j] += digit2char[digit][k]; + } + return res; + + } +}; +``` + +## 思路二 +见[此处](https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8454/My-C%2B%2B-solution-use-DFS). +有时间了再自己实现一下。