题目
思路
对于这种无法用有限个for循环写出来的代码,我们采用回溯的方法,穷举
代码实现
public class Test07 {
public static void main(String[] args) {
Test07 test07 = new Test07();
List<String> res = test07.getRes("234");
System.out.println(res);
}
String[] button = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
// 存放结果组合
List<String> res = new ArrayList<>();
// 存放临时变量
StringBuilder temp = new StringBuilder();
public List<String> getRes(String num) {
combine(num,0);
return res;
}
public void combine(String num,int index) {
// 递归截止点
if (num.length() == index) {
res.add(temp.toString());
return;
}
// 通过输入来获取字母列表
String s = button[num.charAt(index) - '0'];
for (int i = 0; i < s.length(); i++) {
temp.append(s.charAt(i));
combine(num, index + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}