您的位置:首页 > 其它

17. Letter Combinations of a Phone Number

2016-04-20 23:08 281 查看
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"].


思路:就是设置一个字典,然后回溯的组合就行

代码如下(已通过leetcode)

public class Solution {

public List<String> letterCombinations(String digits) {

String[] dicts={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};

List<String> list=new ArrayList<String>();

if(digits==null||digits.length()==0) return list;

String temp="";

backtrace(list,digits,0,dicts,temp);

return list;

}

private void backtrace(List<String> list, String digits, int start, String[] dicts, String temp) {

// TODO Auto-generated method stub

if(start==digits.length()) {

list.add(temp);

return;

}

for(int i=start;i<digits.length();i++) {

String str=dicts[digits.charAt(i)-'0'];

for(int j=0;j<str.length();j++) {

temp=temp+str.charAt(j);

backtrace(list, digits, start+1, dicts, temp);

temp=temp.substring(0,temp.length()-1);

}

break;

}

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: