93.复原IP地址
本期本来是很有难度的,不过 大家做完 分割回文串 之后,本题就容易很多了
题目链接/文章讲解:https://programmercarl.com/0093.%E5%A4%8D%E5%8E%9FIP%E5%9C%B0%E5%9D%80.html
视频讲解:https://www.bilibili.com/video/BV1XP4y1U73i/
class Solution {
List<String> ipList = new ArrayList<String>();
StringBuilder ipBuilder = new StringBuilder();
public List<String> restoreIpAddresses(String s) {
restoreHandler(s, 0, 0);
return ipList;
}
public void restoreHandler(String s, int index, int segmentCount) {
if (index == s.length() && segmentCount == 4) {
ipList.add(ipBuilder.toString());
return;
}
if (index == s.length() || segmentCount == 4) {
return;
}
for (int i = index; i < s.length() && (i - index) < 3 && Integer.parseInt(s.substring(index, i + 1)) <= 255; i++) {
if ((i - index) > 1 && s.charAt(index) == '0') {
continue;
}
ipBuilder.append(s.substring(index, i + 1));
if (segmentCount < 3) {
ipBuilder.append(".");
}
segmentCount++;
restoreHandler(s, i + 1, segmentCount);
segmentCount--;
ipBuilder.delete(index + segmentCount, i + 1 + segmentCount);
}
}
}
78.子集
子集问题,就是收集树形结构中,每一个节点的结果。 整体代码其实和 回溯模板都是差不多的。
题目链接/文章讲解:https://programmercarl.com/0078.%E5%AD%90%E9%9B%86.html
视频讲解:https://www.bilibili.com/video/BV1U84y1q7Ci
class Solution {
List<List<Integer>> subsetsList = new ArrayList<>(); // 存放符合条件结果的集合
LinkedList<Integer> currentSubset = new LinkedList<>(); // 用来存放当前子集
public List<List<Integer>> subsets(int[] nums) {
backtrack(nums, 0);
return subsetsList;
}
private void backtrack(int[] nums, int index) {
subsetsList.add(new ArrayList<>(currentSubset)); // 添加当前子集到结果列表
if (index >= nums.length) {
return;
}
for (int i = index; i < nums.length; i++) {
currentSubset.add(nums[i]); // 选择当前元素
backtrack(nums, i + 1); // 递归生成剩余子集
currentSubset.removeLast(); // 撤销选择
}
}
}
90.子集II
大家之前做了 40.组合总和II 和 78.子集 ,本题就是这两道题目的结合,建议自己独立做一做,本题涉及的知识,之前都讲过,没有新内容。
题目链接/文章讲解:https://programmercarl.com/0090.%E5%AD%90%E9%9B%86II.html
视频讲解:https://www.bilibili.com/video/BV1vm4y1F71J
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Solution {
private List<List<Integer>> result = new ArrayList<>();
private LinkedList<Integer> currentPath = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] numbers) {
Arrays.sort(numbers);
generateSubsetsHelper(numbers, 0);
return result;
}
private void generateSubsetsHelper(int[] numbers, int index) {
result.add(new ArrayList<>(currentPath));
for (int i = index; i < numbers.length; i++) {
if (i > index && numbers[i - 1] == numbers[i]) {
continue;
}
currentPath.add(numbers[i]);
generateSubsetsHelper(numbers, i + 1);
currentPath.removeLast();
}
}
}