leetcode17_电话号码的字母组合
回溯中最需要注意的问题是——对于深度的控制是万万不能写成循环的形式的。应该是在对宽度进行遍历的时候+1,然后在回溯函数开头进行控制。
private void backtracking(String digits, int idx) {
if(idx == digits.length()) { // 相当于depth <= digits.lengt()
ans.add(strBuilder.toString());
return;
}
String oneNumStr = dicts[digits.charAt(idx)-'0'];
for(int i = 0; i < oneNumStr.length(); i++) {
strBuilder.append(oneNumStr.charAt(i));
backtracking(digits, idx+1); //对深度的控制显示这儿,相当于depth++
strBuilder.deleteCharAt(strBuilder.length()-1);
}
}
虽然相当于,但是万万不能显式地写成循环的形式!!!
而具体的函数调用栈是:
idx(深度) | i(宽度) |
---|---|
0 | 0 |
1 | 0 |
2 | 0 |
0 | 1 |
1 | 1 |
2 | 1 |
总的函数: |
class Solution {
private List<String> ans = new ArrayList();
private StringBuilder strBuilder = new StringBuilder();
private String[] dicts = {
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
};
private void backtracking(String digits, int idx) {
if(idx == digits.length()) {
ans.add(strBuilder.toString());
return;
}
String oneNumStr = dicts[digits.charAt(idx)-'0'];
for(int i = 0; i < oneNumStr.length(); i++) {
strBuilder.append(oneNumStr.charAt(i));
backtracking(digits, idx+1);
strBuilder.deleteCharAt(strBuilder.length()-1);
}
}
public List<String> letterCombinations(String digits) {
if(digits.length() == 0 || digits == null) return ans;
backtracking(digits, 0);
return ans;
}
}