LeetCode之17. Letter Combinations of a Phone Number

本文探讨了如何通过深度优先搜索(DFS)和宽度优先搜索(BFS)算法,解决电话号码对应的所有可能字母组合问题。提供了两种解决方案的代码示例,一种使用FIFO队列实现BFS,另一种采用递归实现DFS。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

17. Letter Combinations of a Phone Number

Medium

1823254FavoriteShare

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.

题目核心意思:

              就是2-9分别对应手机的9宫格上的字母,问一共能产生多少种字母组合;

 

别人的代码:

方法一:FIFO + BFS实现

public List<String> letterCombinations(String digits) {
		LinkedList<String> ans = new LinkedList<String>();// FIFO
		if(digits.isEmpty())  // 非空判断
                    return ans;
		String[] mapping = 
                    new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

		ans.add("");
		for(int i =0; i<digits.length();i++){ // 开始进行BFS
			int x = Character.getNumericValue(digits.charAt(i));
			while(ans.peek().length()==i){ 
				String t = ans.remove();
				for(char s : mapping[x].toCharArray())
					ans.add(t+s);
			}
		}
		return ans;
}

1)使用的是先进先出的队列FIFO来进行宽度优先搜索BFS,搜索的树如下:

// Graph/tree visualization for digits = "239"

                                              ""
              a                               b                                 c                  
    d         e         f           d         e         f             d         e         f       
 w x y z   w x y z   w x y z     w x y z   w x y z   w x y z       w x y z   w x y z   w x y z

Each letter or empty string ("") is a node in the tree. The edges are the implicit lines between parent and child nodes in this tree.

public List<String> letterCombinations(String digits) {
		LinkedList<String> ans = new LinkedList<String>();
		if(digits.isEmpty()) return ans;
		String[] mapping 
                        = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
		ans.add("");
		while(ans.peek().length()!=digits.length()){
			String remove = ans.remove();
			String map = mapping[digits.charAt(remove.length())-'0']; // 取数组下标的方式
			for(char c: map.toCharArray()){
				ans.addLast(remove+c);
			}
		}
		return ans;
}

1)这段代码更好理解,更符合通常的BFS的模板代码的格式;

 

方法2:

DFS(深度优先搜索 + 递归实现)

Recursive Solution Time Complexity 3^n, n is length of string ? 不理解为什么是3^n的复杂度;

class Solution {
    String[] store = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList();
        if(digits == null || digits.length()==0)
            return result;
        helper(result,digits, new StringBuilder(),0);
        return result;
    }
    private void helper(List<String> result, String digits, StringBuilder runStr, int idx){
        if(idx == digits.length()){
            result.add(runStr.toString());
            return;
        }    
        char[] chars = store[digits.charAt(idx)-'0'].toCharArray();
        for(char c : chars){
            helper(result,digits, runStr.append(c),idx+1);
            runStr.deleteCharAt(runStr.length()-1); // 删除runStr当前的最后一个字符,实现回溯
        }
    }
}

 

DFS + 递归实现:(此题的最快解法)

class Solution {
   
    public List<String> letterCombinations(String digits) {
        //把table上的数字对应的字母列出来,当输入为2是,digits[2]就是2所对应的"abc"
        String[] table = new String[] 
                             {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        List<String> list = new ArrayList<String>();
        //index从0开始,即digits的第一个数字
        letterCombinations(list,digits,"",0,table);
        return list;
    }
    
    private void letterCombinations (List<String> list, String digits, 
                                    String curr, int index,String[] table) {
        //最后一层退出条件
        if (index == digits.length()) {
            if(curr.length() != 0) list.add(curr);
            return;
        }
        
        //找到数字对应的字符串
        String temp = table[digits.charAt(index) - '0'];
        for (int i = 0; i < temp.length(); i++) {
            //每次循环把不同字符串加到当前curr之后
            String next = curr + temp.charAt(i);
            //进入下一层
            letterCombinations(list,digits,next,index+1,table);
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值