Leetcode: Combination 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"].

Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

Solve the problem on leetcode

这道题很像之前我们解决的Subset和Permutaion排列组合的题,所以用起dfs也很直观。

为了方便我们按照电话上的按键创造一个字符矩阵 Char[ ][ ] table, 用来存储电话按键的字符,用按键的数字做行,里面的字符做列,这样取起来比较容易。每次我们取digits的第一位字符,然后进入它所在矩阵的那一行做从 i = 0 -> 结尾的搜索,在取完这一位字符的时候,传入下一层递归时候我们传入除去第一位剩下的String。这样做的好处为,我们可以固定的取第一位字符,而且添加进res的条件也很直观,一直到digits的长度为0为止。

public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        char[][] table = {{},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
        ArrayList<String> res = new ArrayList<String>();
        dfs(digits,table,"",res);
        return res;
    }
    
    public void dfs(String digits, char[][] table, String tmp, ArrayList<String> res){
        if (digits.length()==0){
            res.add(tmp);
            return;
        }
        for(int i=0; i<table[digits.charAt(0) - '0' - 1].length;i++)
            dfs(digits.substring(1),table,tmp+table[digits.charAt(0)-'0'-1][i],res);
    }
}


几点注意的地方:

1.  数字1所对应的是空集,不要忘了

2.  char字符转换成数字 digits.charAt(0) - '0' - 1, 减去'0'是为了转换成int,再减去1是为了找到对应的行

3.  tmp直接添加字符传入递归参数,这样返回后不用截取tmp

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值