93.复原IP地址
完成
思路:
本题和分割回文子串结构上一致,需要注意的是本题明确了只能分成四段,因此引入一个变量来记录分割段数。
代码
class Solution {
public List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if(s.length()>12) return res;
backtracking(s, 0, 0);
return res;
}
// pointNum是分割点的数量,也代表已经分割好的ip地址段数
public void backtracking(String s, int startIndex, int pointNum){
if(pointNum == 3){
// 验证第四段是否合法
if(isValid(s, startIndex, s.length()-1)){
res.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if(isValid(s, startIndex, i)){
// 分割出一段
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
pointNum++;
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;
}
if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
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) { // 如果⼤于255了不合法
return false;
}
}
return true;
}
}
78.子集
完成
思路:
之前的问题,结果都是在叶子节点取得。子集问题的特殊性就在于其结果是树上的所有节点。
代码
class Solution {
public List<List<Integer>> res = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backtracking(nums, 0);
return res;
}
public void backtracking(int[] nums, int startIndex){
res.add(new ArrayList<>(path)); // 记录所有节点,都是结果
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
backtracking(nums, i+1);
path.removeLast();
}
}
}
90.子集II
完成
思路:
先排序,横向遍历时如果和前一个元素相同就跳过
代码
class Solution {
public List<List<Integer>> res = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backtracking(nums, 0);
return res;
}
public void backtracking(int[] nums, int startIndex){
res.add(new ArrayList<>(path)); // 记录所有节点,都是结果
for (int i = startIndex; i < nums.length; i++) {
if(i>startIndex && nums[i]==nums[i-1]) continue;
path.add(nums[i]);
backtracking(nums, i+1);
path.removeLast();
}
}
}