代码随想录算法训练营二十八天 第七章 | 93.复原IP地址 78.子集 90.子集II
93.复原IP地址
class Solution {
public List<String> result = new ArrayList<>();
public StringBuffer str = new StringBuffer();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) return result;
test(s, 0, 0);
return result;
}
public void test(String s, int startIndex, int num) {
if (num == 3) {
if (isfuhe(s, startIndex, s.length() - 1)){
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isfuhe(s, startIndex, i)) {
s = s.substring(0, i+1) + "." + s.substring(i+1);
num++;
test(s,i+2,num);
num--;
s = s.substring(0, i+1) + s.substring(i+2);
} else {
break;
}
}
}
public boolean isfuhe(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 {
public List<List<Integer>> result = new ArrayList<>();
public LinkedList<Integer> paths = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
result.add(new ArrayList<>());
test(nums,0);
return result;
}
public void test(int[] nums, int startIndex) {
for (int i = startIndex; i < nums.length; i++) {
paths.add(nums[i]);
result.add(new ArrayList<>(paths));
test(nums, i+1);
paths.removeLast();
}
}
}
90.子集II
class Solution {
public List<List<Integer>> result = new ArrayList<>();
public LinkedList<Integer> paths = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
test(nums, 0);
return result;
}
public void test(int[] nums, int startIndex) {
result.add(new ArrayList<>(paths));
for (int i = startIndex; i < nums.length; i++) {
if (i > startIndex && nums[i] == nums[i - 1]) {
continue;
}
paths.add(nums[i]);
test(nums, i+1);
paths.removeLast();
}
}
}