leetcode 216
题目链接
like leetcode 77
思路:
- 基本思路和leetcode 77 类似
- 注意剪枝内容
- 题目要求:
Only numbers 1 through 9 are used.
- 所以当树画到
9 - (k-path.size())——还剩余能加入的数字
- 题目要求:
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
LinkedList<Integer> path = new LinkedList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(k, n, 1);
return res;
}
public void backtracking(int k, int n, int index) {
if (path.size() == k) {
if (sum == n)
res.add(new ArrayList<>(path));
return;
}
//for(int i = index; i <= 9; ++i)
for (int i = index; i <= 9 - (k - path.size()) + 1; ++i) {
sum += i;
path.add(i);
backtracking(k, n, i + 1);
sum -= i;
path.removeLast();
}
}
}
leetcode 17
思路:
- 纵向递归深度
== digits.length()
- 横向遍历——遍历的是每个数字所对应的string,like 2—
"abc"
class Solution {
List<String> res = new ArrayList<>();
StringBuilder temp = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits.length() == 0)
return res;
//把数字和字母对应存储
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backTracking(digits, numString, 0);
return res;
}
public void backTracking(String digits, String[] numString, int num) {
if (num == digits.length()) {
res.add(temp.toString());
return;
}
//str 表示当前num对应的字符串
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracking(digits, numString, num + 1);
//剔除末尾的继续尝试
temp.deleteCharAt(temp.length() - 1);
}
}
}