93.复原IP地址
93. 复原 IP 地址 - 力扣(LeetCode)
本题本质上也是切割问题,只是多了逗点的处理,可以在回溯函数中加入逗点个数的参数,以便控制回溯何时结束,并且这里判断最后一个字串是否合法的过程,放在了开始,和分割回文串不同
class Solution {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
backTracking(new StringBuilder(s), 0, 0);
return result;
}
public void backTracking(StringBuilder sb, int startIndex, int pointSum) {
if (pointSum == 3) {
if (isVaild(sb, startIndex, sb.length() - 1)) {
result.add(sb.toString());
}
return;
}
for (int i = startIndex; i < sb.length(); i++) {
if (isVaild(sb, startIndex, i)) {
sb.insert(i + 1, '.');
pointSum++;
backTracking(sb, i + 2, pointSum);
sb.deleteCharAt(i + 1);
pointSum--;
}
}
}
//区间是左闭右闭
public boolean isVaild(StringBuilder sb, int start, int end) {
if (start > end) {
return false;
}
if (end >= start + 3) {
return false;
}
if (sb.charAt(start) == '0' && start != end) {
return false;
}
int sum = 0;
for (int i = start; i <= end; i++) {
if (sb.charAt(i) > '9' || sb.charAt(i) < '0') { //非法字符
return false;
}
sum = sum * 10 + (sb.charAt(i) - '0');
if (sum > 255) {
return false;
}
}
return true;
}
}
78.子集
78. 子集 - 力扣(LeetCode)
子集和组合以及切割问题不同的是,并不需要等到叶子节点再加入结果,非叶子节点也要加入
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums, 0);
return result;
}
public void backTracking(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]);
backTracking(nums, i + 1);
path.removeLast();
}
}
}
90.子集II
90. 子集 II - 力扣(LeetCode)
本题相比于上一题是多了重复的数字,需要去重,相当于是集合问题与组合总和2的结合
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> subsetsWithDup(int[] nums) {
used = new boolean[nums.length];
Arrays.fill(used, false);
Arrays.sort(nums);
backTracking(nums, 0);
return result;
}
public void backTracking(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;
path.add(nums[i]);
used[i] = true;
backTracking(nums, i + 1);
path.removeLast();
used[i] = false;
}
}
}