class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
StringBuilder sb = new StringBuilder(s);
backtracking(res, sb, 0, 0);
return res;
}
private void backtracking(List<String> res, StringBuilder sb, int points, int startIdx) {
if (points == 3) {
if (isValid(sb, startIdx, sb.length() - 1)) {
res.add(sb.toString());
}
return;
}
for (int i = startIdx; i < sb.length(); i++) {
if (isValid(sb, startIdx, i)) {
sb.insert(i + 1, '.');
points += 1;
backtracking(res, sb, points, i + 2);
sb.deleteCharAt(i + 1);
points -= 1;
} else break;
}
}
private boolean isValid(StringBuilder 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) < '0' || s.charAt(i) > '9') return false;
int digit = s.charAt(i) - '0';
num = num * 10 + digit;
if (num > 255) return false;
}
return true;
}
}
subset问题
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
backtracking(res, list, nums, 0);
return res;
}
private void backtracking(List<List<Integer>> res, List<Integer> list, int[] nums, int idx) {
res.add(new ArrayList<>(list));
for (int i = idx; i < nums.length; i++) {
list.add(nums[i]);
backtracking(res, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
backtracking(res, list, nums, visited, 0);
return res;
}
private void backtracking(List<List<Integer>> res, List<Integer> list, int[] nums, boolean[] visited, int idx) {
res.add(new ArrayList<>(list));
for (int i = idx; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue;
list.add(nums[i]);
visited[i] = true;
backtracking(res, list, nums, visited, i + 1);
list.remove(list.size() - 1);
visited[i] = false;
}
}
}