【Leetcode-17】Letter Cominations of a Phone Number

【Leetcode-17】Letter Cominations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
在这里插入图片描述

Example:

Input: “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.

使用回溯解决这个问题

class Solution17 {
    Map<String,String> map=new  HashMap<String,String> ();
	 List<String> list=new ArrayList<String>();
	
	
	public List<String> letterCombinations(String digits) {
		 map.put("2", "abc");
	     map.put("3", "def");
	     map.put("4", "ghi");
	     map.put("5", "jkl");
	     map.put("6", "mno");
	     map.put("7", "pqrs");
	     map.put("8", "tuv");
	     map.put("9", "wxyz");
	     backtrack("",digits);
         if(digits.length()==0){
             return new ArrayList<String>();
         }
	     return list;
	 }
	private void backtrack(String combination,String next_digits) {
		if(next_digits.length()==0) {
			list.add(combination);
            
		}
		else {
			//取下一个数
			String str=map.get(next_digits.substring(0,1));
			int len=str.length();
            for(int i=0;i<len;i++) {
			   backtrack(combination+str.substring(i,i+1), next_digits.substring(1));
			   
				/*
				 * String s=combination; 
				 * combination+=str.substring(i,i+1);
				 * backtrack(combination, next_digits.substring(1)); 
				 * combination=s;
				*/
			}
			
		}
		
	
	}
    
}
发布了34 篇原创文章 · 获赞 4 · 访问量 1345

猜你喜欢

转载自blog.csdn.net/zj20165149/article/details/103935827
今日推荐