今日任务
回溯算法理论基础
77. 组合
216.组合总和III
17.电话号码的字母组合
回溯算法理论基础
只要有递归就会有回溯。回溯法的本质是穷举,因此效率比较低,因为没得选,只能用回溯法。
77. 组合
题目链接: . - 力扣(LeetCode)
class Solution {
public List<List<Integer>> result = new ArrayList<>();
public LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return result;
}
public void combineHelper(int n, int k, int startIndex) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i <= n; i++) {
path.add(i);
combineHelper(n, k, i + 1);
path.removeLast();
}
}
}
216.组合总和III
题目链接: . - 力扣(LeetCode)
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
restrospective(k,n, 1);
return result;
}
public void restrospective(int k, int n, int startIndex){
if (path.size() == k) {
if (path.stream().mapToInt(Integer::intValue).sum() == n) {
result.add(new ArrayList<>(path));
}
return;
}
for (int i = startIndex; i < 10; i++) {
path.add(i);
restrospective(k, n, i + 1);
path.remove(path.size() - 1);
}
return;
}
}
17.电话号码的字母组合
题目链接: . - 力扣(LeetCode)
class Solution {
List<String> result = new ArrayList<>();
Map<Character, String> map = new HashMap<Character, String>();
StringBuilder path = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {return result;}
map.put('2',"abc");
map.put('3',"def");
map.put('4',"ghi");
map.put('5',"jkl");
map.put('6',"nmo");
map.put('7',"pqrs");
map.put('8',"tuv");
map.put('9',"wxyz");
restrospective(digits, 0);
return result;
}
public void restrospective(String digits, int startIndex) {
if (path.length() == digits.length()) {
result.add(new String(path));
return;
}
String str = map.get(digits.charAt(startIndex));
for (int i = 0; i < str.length(); i++) {
path.append(str.charAt(i));
restrospective(digits, startIndex + 1);
path.deleteCharAt(path.length() - 1);
}
return;
}
}