Day 28 | 回溯 93.复原IP地址 、78.子集 、 90.子集II
93.复原IP地址
思路:每轮开始的位置需要变化就需要设置start
class Solution {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() < 4 ||s.length() > 12)
return result;
backTrack(s, 0, 0);
return result;
}
private void backTrack(String s, int startIndex, int pointNum) {
if (pointNum == 3) {
if (isValid(s, startIndex, s.length() - 1)) {
result.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++;
backTrack(s, i + 2, pointNum);
pointNum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
} else
break;
}
}
private boolean isValid(String s, int start, int end) {
if (start > end)
return false;
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;
}
}
78.子集
思路:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracing(nums, 0);
return result;
}
private void backTracing(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]);
backTracing(nums, i + 1);
path.removeLast();
}
}
}
90.子集II
思路:利用used数组进行去重
问题:nums[i] == nums[i - 1]去重为什么不用nums[i] == nums[i +1] 解答,编程中的 i 所指都是当前的,要与前一个比较,当前与之前属于已知,后面的是未知。
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> subsetsWithDup(int[] nums) {
if (nums.length == 0) {
result.add(path);
return result;
}
Arrays.sort(nums);
used = new boolean[nums.length];
backTracing(nums, 0);
return result;
}
private void backTracing(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;
}
used[i] = true;
path.add(nums[i]);
backTracing(nums, i + 1);
path.removeLast();
used[i] = false;
}
}
}
原文地址:https://blog.csdn.net/m0_46554918/article/details/135766959
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!