今日任务
93.复原IP地址
78.子集
90.子集II
93.复原IP地址
题目链接: . - 力扣(LeetCode)
class Solution {
List<String> path = new ArrayList<>();
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
retrospective(s, 0);
return result;
}
private void retrospective(String s, int startIndex) {
if (path.size() == 4 && startIndex == s.length()) {
String str = String.join(".", path);
result.add(str);
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex, i)) {
path.add(s.substring(startIndex, i + 1));
retrospective(s, i + 1);
path.remove(path.size() - 1);
}
}
return;
}
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.子集
题目链接: . - 力扣(LeetCode)
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
result.add(new ArrayList<>());
retrospective(path, nums, 0);
return result;
}
public void retrospective(List<Integer> path, int[] nums, int startIndex) {
if (startIndex == nums.length) {return;}
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
result.add(new ArrayList<>(path));
retrospective(path, nums, i + 1);
path.remove(path.size() - 1);
}
return;
}
}
90.子集II
题目链接: . - 力扣(LeetCode)
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Set<List<Integer>> set = new HashSet<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
result.add(new ArrayList<>());
Arrays.sort(nums);
retrospective(path, nums, 0);
return result;
}
public void retrospective(List<Integer> path, int[] nums, int startIndex) {
if (startIndex == nums.length) {return;}
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
ArrayList<Integer> tmpPath = new ArrayList<>(path);
if (!set.contains(tmpPath)) {
result.add(tmpPath);
set.add(tmpPath);
}
retrospective(path, nums, i + 1);
path.remove(path.size() - 1);
}
return;
}
}