Letter Combinations of a Phone Number (LeetCode)
Question:
https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/
解答:
Combination的问题,一般就是DFS和BFS枚举所有的情况。
BFS好像只有iterative的解法比较普遍,recursive的解法不多见。
DFS可以iterative,也可以recursive.
Iterative解法DFS用stack, BFS用queue。 注意stack取值是stack.top(), queue是queue.front().
class Solution { public: vector<string> letterCombinations(string digits) { std::map<char, string> keyboard; keyboard['0'] = " "; keyboard['2'] = "abc"; keyboard['3'] = "def"; keyboard['4'] = "ghi"; keyboard['5'] = "jkl"; keyboard['6'] = "mno"; keyboard['7'] = "pqrs"; keyboard['8'] = "tuv"; keyboard['9'] = "wxyz"; vector<string> ret; //std::stack<std::pair<int, string>> container; std::queue<std::pair<int, string>> container; std::pair<int, string> sp = std::make_pair(0, ""); container.push(sp); while (!container.empty()) { //sp = container.top(); sp = container.front(); container.pop(); if (sp.first == digits.size()) { ret.push_back(sp.second); } else { for (int i = 0; i < keyboard[digits[sp.first]].size(); i++) { std::pair<int, string> newSp(sp); newSp.first++; newSp.second.push_back(keyboard[digits[sp.first]][i]); container.push(newSp); } } } return ret; } };