加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

[LeetCode] 017. Letter Combinations of a Phone Number (Mediu

发布时间:2020-12-13 20:16:59 所属栏目:PHP教程 来源:网络整理
导读:索引:[LeetCode] Leetcode 题解索引 (C/Java/Python/Sql) Github: https://github.com/illuz/leetcode 017.Letter_Combinations_of_a_Phone_Number (Medium) 链接 : 题目:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ 代码(

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


017.Letter_Combinations_of_a_Phone_Number (Medium)

链接

题目:https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/
代码(github):https://github.com/illuz/leetcode

题意

在手机上按字母,给出按的数字键,问所有的按的字母的情况。

分析

DFS 过去是比较轻松的写法。

代码

C++:

class Solution { private: const string alpha[10] = { " ","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" }; void dfs(vector<string> &res,string &ab,string &digits,int cur) { if (cur >= digits.length()) { res.push_back(ab); return; } for (auto &a : alpha[digits[cur] - '0']) { ab.push_back(a); dfs(res,ab,digits,cur + 1); ab.pop_back(); } } public: vector<string> letterCombinations(string digits) { vector<string> res; string alphas; dfs(res,alphas,0); return res; } };


Java:

public class Solution { private String[] alpha = new String[] { " ","wxyz" }; private StringBuilder word; private void dfs(List<String> res,String digits,int cur) { if (cur >= digits.length()) { res.add(word.toString()); } else { for (int i = 0; i < alpha[digits.charAt(cur) - '0'].length(); ++i) { word.append(alpha[digits.charAt(cur) - '0'].charAt(i)); dfs(res,cur + 1); word.deleteCharAt(word.length() - 1); } } } public List<String> letterCombinations(String digits) { List<String> ret = new ArrayList<String>(); word = new StringBuilder(); dfs(ret,0); return ret; } }


Python:

class Solution: # @return a list of strings,[s1,s2] def letterCombinations(self,digits): alpha = [" ","wxyz"] res = [] word = [] def dfs(cur): if cur >= len(digits): res.append(''.join(word)) else: for x in alpha[(int)(digits[cur]) - (int)('0')]: word.append(x) dfs(cur + 1) word.pop() dfs(0) return res


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读