[LeetCode] Letter Combinations of a Phone Number
http://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/
这道题是LeetCode上独立做出来的第一道题, dfs.
这道题一开始总wa, 后来发现是stl string用错了, 我初始化是这么写的 string str(10); 导致所有str都是长10, 估计LeetCode会做检查, 所以就wa了, 后来就采用了先push, 递归后pop的方法,ac了.
string str; string arr[10] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; class Solution { public: vector<string> re; void dfs(string digits, int cur) { if (cur == digits.size()) { re.push_back(str); } else { int index = digits[cur] - '0'; for (int i = 0; i < arr[index].size(); ++i) { str.push_back(arr[index][i]); dfs(digits, cur + 1); str.pop_back(); } } } vector<string> letterCombinations(string digits) { re.clear(); dfs(digits, 0); return re; } };