Leetcode 93.复原IP地址
题目链接
思路:回溯算法
代码:
class Solution {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) {
return result;
}
backtracking(s, 0, 0);
return result;
}
// startIndex: 搜索的起始位置,pointNum: 添加逗点的数量
private void backtracking(String s, int startIndex, int pointNum) {
// 分割四段,逗点数量为3
if (pointNum == 3) {
// 判断第四段⼦字符串是否合法,如果合法就放进result中
if (isValid(s, startIndex, s.length() - 1)) {
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex, i)) {
//在str的后⾯插⼊⼀个逗点
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
pointNum++;
// 插⼊逗点之后下⼀个⼦串的起始位置为i+2
backtracking(s, i + 2, pointNum);
// 回溯
pointNum--;
// 回溯删掉逗点
s = s.substring(0, i + 1) + s.substring(i + 2);
} else {
// 不合法,直接结束本层循环
break;
}
}
}
// 判断字符串s在左闭⼜闭区间[start, end]所组成的数字是否合法
private boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
// 0开头的数字不合法
if (s.charAt(start) == '0' && start != end) {
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
// 遇到⾮数字字符不合法
if (s.charAt(i) > '9' || s.charAt(i) < '0') {
return false;
}
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) {
return false;
}
}
return true;
}
}
Leetcode 78.子集
题目链接
思路:回溯算法,常规回溯逻辑,比较简单
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backtracking(nums, 0);
return result;
}
private void backtracking(int[] nums, int startIndex) {
// 收集子集,要放在终止添加的上面,否则会漏掉自己
result.add(new ArrayList<>(path));
if (startIndex >= nums.length) {
return;
}
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
backtracking(nums, i + 1);
// 回溯
path.remove(path.size() - 1);
}
}
}
Leetcode 90.子集II
题目链接
思路:回溯算法,去重,思路和40. 组合总和 II一样
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> subsetsWithDup(int[] nums) {
used = new boolean[nums.length];
Arrays.fill(used, false);
// 剪枝操作
Arrays.sort(nums);
backtracking(nums, 0);
return result;
}
private void backtracking(int[] nums, int startIndex) {
result.add(new ArrayList<>(path));
if (startIndex >= nums.length){
return;
}
for (int i = startIndex; i < nums.length; i++){
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]){
continue;
}
path.add(nums[i]);
used[i] = true;
backtracking(nums, i + 1);
// 回溯
path.remove(path.size() - 1);
used[i] = false;
}
}
}