LeetCode93 复原IP地址
题目链接:https://programmercarl.com/0093.%E5%A4%8D%E5%8E%9FIP%E5%9C%B0%E5%9D%80.html
代码:
public class code93 {
List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
findPath(s, 0, 0);
return res;
}
private void findPath(String s, int startIndex, int pointSum) {
// 收割结果
if (pointSum == 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);
pointSum++;
findPath(s, i + 2, pointSum);
pointSum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
} else {
break;
}
}
}
// 判断字串是否是有效ip的函数
private boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
if (s.charAt(start) == '0' && start != end) {
return false;
}
long num = Long.parseLong(s.substring(start, end + 1));
if (num < 0 || num > 255) {
return false;
}
return true;
}
}
注意区间选取,还有就是isValid函数中将字符串转为数字要注意int类型不够大,要使用long
LeetCode78 子集
题目链接:https://programmercarl.com/0078.%E5%AD%90%E9%9B%86.html
代码:
public class code78 {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
findPath(nums, 0);
return res;
}
private void findPath(int[] nums, int startIndex) {
res.add(new ArrayList<>(path));
// 遍历到叶子节点终止递归
if (startIndex >= nums.length) return;
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
findPath(nums, i + 1);
path.removeLast(); // 回溯
}
}
}
注意收割结果的时机,因为是每个节点都要收割,所以递归一开始就是收割结果的时候
LeetCode90 子集II
题目链接:https://programmercarl.com/0090.%E5%AD%90%E9%9B%86II.html
代码:
public class code90 {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
Arrays.sort(nums);
findPath(nums, 0);
return res;
}
private void findPath(int[] nums, int startIndex) {
res.add(new ArrayList<>(path));
// 遍历到叶子节点终止递归
if (startIndex >= nums.length) return;
for (int i = startIndex; i < nums.length; i++) {
if (i > startIndex && nums[i] == nums[i - 1]) {
continue;
}
path.add(nums[i]);
findPath(nums, i + 1);
path.removeLast(); // 回溯
}
}
}
理解树层去重操作