leetcode--17. Letter Combinations of a Phone Number
2016-08-07 13:00
621 查看
Letter Combinations of a Phone Number
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.
Input: Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
BFS
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.
Input: Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
题解
dfsclass Solution { public: vector<string> ans; vector<string> letterCombinations(string digits) { if(digits.empty()) return ans; vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; /* 0 1 2 3 4 5 6 7 8 9 */ string prefix; solve(prefix, digits, dict); return ans; } void solve(string& prefix, string digits, vector<string>& dict){ if(digits.length() == 0){ ans.push_back(prefix); return; } int idx = digits[0] - '0'; for(int i = 0; i < dict[idx].size(); ++i){ prefix.push_back(dict[idx][i]); solve(prefix, digits.substr(1), dict); prefix.pop_back(); } } };
BFS
public class Solution { public List<String> letterCombinations(String digits) { LinkedList<String> ans = new LinkedList<String>(); if(digits.length() == 0) return ans; String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; ans.add(""); for(int i = 0; i < digits.length(); ++i){ int idx = digits.charAt(i) - '0'; while(ans.peek().length() == i){ String t = ans.remove(); for(char c : mapping[idx].toCharArray()) ans.add(t + c); } } return ans; } }
相关文章推荐
- 【leetcode】17. Letter Combinations of a Phone Number
- leetcode 17. Letter Combinations of a Phone Number
- LeetCode *** 17. Letter Combinations of a Phone Number
- 【LeetCode】17. Letter Combinations of a Phone Number
- [LeetCode]--17. Letter Combinations of a Phone Number
- [leetcode] 17. Letter Combinations of a Phone Number
- [LeetCode-Java]17. Letter Combinations of a Phone Number
- 17.leetcode Letter Combinations of a Phone Number(meidum)[递归回溯]
- 个人记录-LeetCode 17. Letter Combinations of a Phone Number
- leetcode:17. Letter Combinations of a Phone Number
- LeetCode - 17. Letter Combinations of a Phone Number
- 【leetcode】17. Letter Combinations of a Phone Number
- leetcode 17. Letter Combinations of a Phone Number
- leetcode 17. Letter Combinations of a Phone Number
- LeetCode 17.Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number LeetCode
- leetcode 17. Letter Combinations of a Phone Number
- LeetCode-17.Letter Combinations of a Phone Number
- Leetcode-17. Letter Combinations of a Phone Number
- (Java)LeetCode-17. Letter Combinations of a Phone Number