Day28
93.复原IP地址
class Solution {
List<String> res = new ArrayList<>();
List<String> path = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
backTracking(s, 0, 0);
return res;
}
public void backTracking (String s, int startIndex, int turn) {
int sum = 0;
StringBuilder sb = new StringBuilder();
for (String ss : path) {
sum += ss.length();
sb.append(ss);
sb.append(".");
}
if (sb.length() > 1) {
sb.deleteCharAt(sb.length() -1);
}
if (path.size() == 4 && sum == s.length() && turn == 4) {
res.add(sb.toString());
return;
}
for (int i = startIndex; i < s.length() && i < startIndex + 3; i++) {
String tmp = s.substring(startIndex, i + 1);
if (check(tmp)) {
path.add(tmp);
backTracking(s, i + 1, turn + 1);
path.remove(path.size() - 1);
}
}
}
public boolean check (String s) {
if (s.charAt(0) == '0' && s.length() > 1) return false;
if (Integer.parseInt(s) > 255) return false;
return true;
}
}
78.子集
如果把子集问题、组合问题、分割问题都抽象为一棵树的话,那么组合问题和分割问题都是收集树的叶子节点,而子集问题是找树的所有节点。
class Solution {
List<List<Integer>> res = new ArrayList<>();
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));
if (startIndex >= nums.length) return;
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
backTracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
90.子集Ⅱ
class Solution {
List<List<Integer>> res = new ArrayList<>();
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));
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]);
backTracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}