leetcode 17 电话号码的字母组合

问题描述:

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

问题连接
leetcode

示例
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
代码
class Solution {
    public List<String> letterCombinations(String digits) {
        	  if(digits.length() == 0) return new ArrayList<String>();
	  char[][] numChar = new char[][]{
		  {'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'}			  
	  };
	  List<String> result = new ArrayList<>();
	  char[] tem  = new char[digits.length()];
	  char[][] temp = new char[digits.length()][];
	  for(int i = 0; i < digits.length(); i ++){
		  temp[i] = numChar[Integer.parseInt(digits.charAt(i)+"") - 2];
	  }
	  //在这上面都是为了让digits出现的字符串中的字符 所对应的字符数组组合成一个二维数组,第一行是第一个字符会出现的可能  第二行是第二个字符出现的可能 。。。。。 直到最后
	  build(result, temp, tem, 0);
	  //这个函数是一个递归函数  每次递归 都是将拿到的字符放入tem数组
	  //比如: 输入的是"23"
	  //那么我们组成的二维数组temp为
	  //{{'a','b','c'},
	  //{'d','e','f'}}
	  //在build 中运行轨迹是:
	  //第一次进入:result 为空 ,temp 上面给出,tem.size = 2,idx = 0;
	  //  foreach 迭代 temp[0]
	  // tem[0] = 'a';
	  //if判断为false 进入第二次
	  //第二次进入:result为空,temp没有变,tem[0] = a  其他为空 idx = 1
	  //foreach 迭代temp[1]
	  //tem[1] = 'd'; 
	  //if 判断为true result加入tem字符数组组成的字符串,'ad'
	  //再进入循环
	  //temp[1] 第二个char
	  //tem[1] = 'e';
	  //if 判断成立true result加入tem字符数组组成的字符串,'ae'
	  //再进入循环
	  //temp[2] 第二个char
	  //tem[2] = 'f';
	  //if 判断成立true result加入tem字符数组组成的字符串,'af'
	  
	  // 这里又回到了第一次进入  的迭代 的第一次迭代结束 再次开始迭代 进入第二次迭代 和上面类似 
	  


	// 结果是 二维数组每个组合都遍历了一次 形成集合
	  return result;
}
private static void build(List<String> result, char[][] temp, char[] tem, int idx){
	  for(char tt : temp[idx]){
		  tem[idx] = tt;
		  if(idx == temp.length - 1){
			  result.add(new String(tem));
		  }else{
			  build(result, temp, tem, idx + 1);
		  }
	  }
}
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值