LeetCode017——电话号码的字母组合

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82177357

原题链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/

题目描述:

知识点:回溯算法

思路:递归回溯法穷举所有可能的组合

本题是回溯法的一个经典应用场景。而且该回溯法没有剪枝操作的优化空间。实现过程中需要注意以下几点内容:

(1)当输入字符串为空时,直接返回空字符数组。

(2)利用哈希表存储每个数字对应的字符串,简化代码量。

(3)回溯过程中注意相关变量的手动回溯

(4)在Solution类中新建内部的私有成员变量,可以防止递归函数中一直传递该变量。

JAVA代码:

public class Solution {
	
	private List<String> list;
	private HashMap<Character, String> hashMap;
	
	public List<String> letterCombinations(String digits) {
		list = new ArrayList<>();
		if(digits.length() == 0) {
			return list;
		}
		hashMap = new HashMap<>();
		hashMap.put('2', "abc");
		hashMap.put('3', "def");
		hashMap.put('4', "ghi");
		hashMap.put('5', "jkl");
		hashMap.put('6', "mno");
		hashMap.put('7', "pqrs");
		hashMap.put('8', "tuv");
		hashMap.put('9', "wxyz");
		StringBuilder stringBuilder = new StringBuilder();
		letterCombinations(digits, 0, stringBuilder);
		return list;
	}
	
	//stringBuilder中存储了考虑digits中前index - 1个元素所得到的字符串,接下来我们要考虑的是digits中第index个字符
	private void letterCombinations(String digits, int index, StringBuilder stringBuilder) {
		if(index == digits.length()) {
			list.add(stringBuilder.toString());
			return;
		}
		char[] nextChar = hashMap.get(digits.charAt(index)).toCharArray();
		for(int i = 0; i < nextChar.length; i++) {
			stringBuilder.append(nextChar[i]);
			letterCombinations(digits, index + 1, stringBuilder);
			stringBuilder.deleteCharAt(stringBuilder.length() - 1);
		}
	}
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82177357