仔细审题,会发现这是个组合问题,于是我就往回溯的方向去思考了(关于组合的问题可以用回溯哦),可能有小伙伴第一次对回溯有点陌生,我稍微讲讲我对回溯的理解。回溯的本质呢就是穷举,暴力搜索。用来解决那种用for循环嵌套暴力搜索都很难解决的问题。就比如说这个题,用for循环嵌套去解题的话是不是有点窒息呢?
来看看代码吧,思想都在注释里面,要是看不懂的话,拿出纸和笔推算一下就懂了。
class Solution {
//用于获取结果集
List<String> result = new ArrayList<>();
//每次迭代获取一个字符串,都会涉及到字符串的拼接,所以这里采用更高效的StringBuilder
StringBuilder path = new StringBuilder();
public List<String> letterCombinations(String digits) {
//前置条件
if(digits == null || digits.length() < 1) return result;
//开始处理字符串。
letterCombinationsHeper(digits, 0);
return result;
}
//是递归,也是遍历字符串(不理解的话接着往下看吧)。
//遍历字符串,tx则为遍历的下标
public void letterCombinationsHeper(String digits, int tx){
//终止条件。
if(path.length() == digits.length()){
result.add(path.toString());
return;
}
//这些值都是固定的,我把它们穷举出来。
String temp = "";
switch(digits.charAt(tx)){
case '2':
temp = "abc";
break;
case '3':
temp = "def";
break;
case '4':
temp = "ghi";
break;
case '5':
temp = "jkl";
break;
case '6':
temp = "mno";
break;
case '7':
temp = "pqrs";
break;
case '8':
temp = "tuv";
break;
case '9':
temp = "wxyz";
break;
}
//看似遍历digit字符串,实则遍历temp字符串。
for(int i = 0; i < temp.length(); ++i){
path.append(temp.charAt(i));
letterCombinationsHeper(digits, tx +1);
//回溯(回溯的精华在这里了)
path.deleteCharAt(path.length() -1);
}
}
}