2024/9/10 Hot100 回溯

This commit is contained in:
linlihong 2024-09-10 17:11:14 +08:00
parent c8f22deef1
commit 0b1434aacb
3 changed files with 165 additions and 0 deletions

View File

@ -0,0 +1,66 @@
package com.cool.hot100.backtracking;
import java.util.*;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/10/11:06
* DayNumber 1
* Hard 2
* Level ?
*/
public class Num17 {
List<String> res = new ArrayList<>();
char[] chars;
public List<String> letterCombinations(String digits) {
if ("".equals(digits)) {
return new ArrayList<>();
}
chars = new char[digits.length()];
dfs(0, digits);
return new ArrayList<>(res);
}
private void dfs(int index, String digits) {
if (index >= digits.length()) {
res.add(new String(chars));
return;
}
String str = getLetter(digits.charAt(index)-'0');
for (int i = 0; i < str.length(); i++) {
chars[index] = str.charAt(i);
dfs(index + 1, digits);
}
}
private String getLetter(int num) {
switch (num) {
case 2:
return "abc";
case 3:
return "def";
case 4:
return "ghi";
case 5:
return "jkl";
case 6:
return "mno";
case 7:
return "pqrs";
case 8:
return "tuv";
case 9:
return "wxyz";
default:
return "";
}
}
}

View File

@ -0,0 +1,43 @@
package com.cool.hot100.backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/10/15:25
* DayNumber 3
* Hard 2
* Level ?
*/
public class Num22 {
int n;
char[] chars;
List<String> list = new ArrayList<>();
public List<String> generateParenthesis(int n) {
this.n = n;
chars = new char[n * 2];
dfs(0, 0);
return list;
}
private void dfs(int num, int left) {
if (num == n * 2) {
list.add(new String(chars));
return;
}
if (left < n) {
chars[num] = '(';
dfs(num + 1, left + 1);
}
if (left * 2 > num) {
chars[num] = ')';
dfs(num + 1, left);
}
}
}

View File

@ -0,0 +1,56 @@
package com.cool.hot100.backtracking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/10/14:21
* DayNumber 2
* Hard 2
* Level ?
*/
public class Num39 {
List<List<Integer>> resList = new ArrayList<>();
int maxIndex;
List<Integer> list = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
for (int i = 0; i < candidates.length; i++) {
if (candidates[i] > target) {
maxIndex = i - 1;
break;
} else if (i == candidates.length - 1) {
maxIndex = i;
}
}
if (candidates[0] > target || maxIndex < 0) {
return resList;
}
dfs(candidates, target, maxIndex);
return resList;
}
private void dfs(int[] candidates, int target, int index) {
if (target == 0) {
resList.add(new ArrayList<>(list));
return;
}
if (target < 0 || index < 0) {
return;
}
if (candidates[index] <= target) {
list.add(candidates[index]);
dfs(candidates, target - candidates[index], index);
list.remove(list.size() - 1);
}
dfs(candidates, target, index - 1);
}
}