leetcode 216 组合总和 III
题目链接
做题思路
思路同77. 组合 - 力扣(LeetCode),依然套用回溯。
解决方法
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
bulidhelper(k, n, 1, 0);
return res;
}
private void bulidhelper(int k, int n, int startIndex, int sum) {
if (path.size() == k && sum == n){
res.add(new LinkedList(path));
return;
}
for (int i = startIndex; i <= 9; i++) {
path.add(i);
sum += i;
bulidhelper(k, n, i + 1, sum);
path.removeLast();
sum -=i;
}
}
}
leetcode 17 电话号码的字母组合
题目链接
做题思路
思路同77. 组合 - 力扣(LeetCode),依然套用回溯。但需要建立一个map,使得数字与字母对应。其余便是普通的递归+回溯。
解决方法
class Solution {
List<String> res = new LinkedList<>();
StringBuilder path = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return res;
}
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
bulidHelper(digits, numString, 0);
return res;
}
private void bulidHelper(String digits, String[] numString, int num) {
if (num == digits.length()) {
res.add(path.toString());
return;
}
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
path.append(str.charAt(i));
bulidHelper(digits, numString, num + 1);
path.deleteCharAt(path.length() - 1);
}
}
}