Letter Combinations of a Phone Number
2015-08-01 22:28
274 查看
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png)
A mapping of digit to letters (just like on the telephone buttons) is given below.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png)
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
简单的回溯实现
class Solution { public: //回溯法 void DFS(string digits, int n, int curIndex, string curStr, unordered_map<char, string> &cmap, vector<string> &ans) { if(curIndex > n) return; if(curIndex == n) { ans.push_back(curStr); return; } int tmpLen = cmap[digits[curIndex]].size(); for(int i = 0; i< tmpLen; ++i) { curStr.push_back(cmap[digits[curIndex]][i]); DFS(digits, n, curIndex + 1, curStr, cmap, ans); curStr.pop_back(); } } vector<string> letterCombinations(string digits) { int len = digits.size(); vector<string> ans; if(len >= 1) { unordered_map<char, string> cmap; cmap['2'] = "abc"; cmap['3'] = "def"; cmap['4'] = "ghi"; cmap['5'] = "jkl"; cmap['6'] = "mno"; cmap['7'] = "pqrs"; cmap['8'] = "tuv"; cmap['9'] = "wxyz"; string curStr = ""; DFS(digits, len, 0, curStr, cmap, ans); } return ans; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解