首页 > 其他 > 详细

Letter Combinations of a Phone Number

时间:2014-03-14 18:27:59      阅读:359      评论:0      收藏:0      [点我收藏+]

题目原型:

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.

bubuko.com,布布扣

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.

基本思路:

递归求解

	public ArrayList<String> letterCombinations(String digits)
	{
		ArrayList<String> list = new ArrayList<String>();
		char[] number = digits.toCharArray();//存放电话号码
		int len = number.length;//电话号码长度
		String[] phone = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//字母与数字对应表
		int[] total = {0,0,3,3,3,3,3,4,3,4};//每个数字上有多少个字母
		int[] answer = new int[len];//指示每个数字所对应字母序列的字符位子,如第一个数字是2,如果answer[0] = 0,表示所对应的字符是a即phone[0].charAt[answer[0]]=‘a‘
		combinatons(list,phone, number, answer, 0, len, total);
		return list;
	}
	
	void combinatons(ArrayList<String> list,String[] phone,char[] number , int[] answer , int index , int len , int[] total)
	{
		if(index==len)
		{
			StringBuffer strbuf = new StringBuffer();
			for(int i = 0 ;i<len;i++)
			{
				strbuf.append(phone[number[i]-‘0‘].charAt(answer[i]));
			}
			list.add(strbuf.toString());
			return;
		}
		for(answer[index]=0;answer[index]<total[number[index]-‘0‘];answer[index]++)
		{
			combinatons(list,phone, number, answer, index+1, len, total);
		}
	}



Letter Combinations of a Phone Number,布布扣,bubuko.com

Letter Combinations of a Phone Number

原文:http://blog.csdn.net/cow__sky/article/details/21184979

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!