[LeetCode]Letter Combinations of a Phone Number
来源:互联网 发布:人工智能权威期刊 编辑:程序博客网 时间:2024/05/02 01:55
解题思路:
深度搜索,配合字典的使用。如果把组合看成一颗树,那么就是要从树根找到leaf,在leaf那里把string添加到要返回的vector里面。
实现方面,主要注意 string.c_str() 的巧妙使用。以及最后加入到 结果集合的 str的长度已定要满足与digits长度一致(如果不注意,输入为空时,你会得到一个WA)
class Solution {public: vector<string> letterCombinations(string digits) { map<char, string> dict; dict['2'] = "abc"; dict['3'] = "def"; dict['4'] = "ghi"; dict['5']="jkl"; dict['6']="mno"; dict['7']="pqrs"; dict['8']="tuv"; dict['9']="wxyz"; vector<string> ret; tracking(digits.c_str(), dict, "", ret); return ret; } void tracking(const char* ch, map<char, string> &dict, string str, vector<string> &ret){ if (*ch == '\0'){ if (str.length() > 0) ret.push_back(str); }else{ auto it = dict.find(*ch); if (it != dict.end()){ string tosearch = it->second; int ind = 0; while(ind < tosearch.length()){ tracking(ch+1, dict, str+tosearch[ind], ret); ind++; } }else{ printf("invalid input."); } } }};
0 0
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- LeetCode | Letter Combinations of a Phone Number
- leetcode Letter Combinations of a Phone Number
- Leetcode: Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- c++中string类的用法详解
- Path特效之PathMeasure打造万能路径动效
- GridView+SimpleAdapter的简单使用
- 关于UIImageView 添加UITapGestureRecognizer后传参的问题
- POJ 1835 宇航员
- [LeetCode]Letter Combinations of a Phone Number
- Codeforces Round #283 (Div. 2) B. Secret Combination 构造+枚举
- C++ 无名对象
- 经典SQL语句大全
- UIImage
- 微信公众平台开发教程新手解惑40则
- Java关键字this、super使用总结
- python学习笔记——异常处理
- memorization DEMO