93.復(fù)原IP地址
93. 復(fù)原 IP 地址 - 力扣(LeetCode)
本題本質(zhì)上也是切割問題,只是多了逗點(diǎn)的處理犬绒,可以在回溯函數(shù)中加入逗點(diǎn)個(gè)數(shù)的參數(shù)旺入,以便控制回溯何時(shí)結(jié)束,并且這里判斷最后一個(gè)字串是否合法的過程凯力,放在了開始茵瘾,和分割回文串不同
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--;
}
}
}
//區(qū)間是左閉右閉
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)
子集和組合以及切割問題不同的是,并不需要等到葉子節(jié)點(diǎn)再加入結(jié)果咐鹤,非葉子節(jié)點(diǎn)也要加入
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)
本題相比于上一題是多了重復(fù)的數(shù)字拗秘,需要去重,相當(dāng)于是集合問題與組合總和2的結(jié)合
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;
}
}
}