LeetCode:93. 复原 IP 地址 - 力扣(LeetCode)
1.思路
分割字符,判断被分割的部分是否有效,有效添加逗点,并对最后一段进行判断,终止条件为三个逗点数量。
2.代码实现
class Solution {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) return result;
backtracking(s, 0, 0);
return result;
}
private void backtracking(String s, int startIndex, int pointSum) {
if (pointSum == 3) {
if (isValid(s, startIndex, s.length() - 1)) {
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) { // startIndex作为分割标识存在
if (isValid(s, startIndex, i)) {
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
pointSum++;
backtracking(s, i + 2, pointSum);
pointSum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
} else {
break;
}
}
}
private boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
// 数字不能以0开头
if (s.charAt(start) == '0' && start != end) {
return false;
}
//
int num = 0;
for (int i = start; i <= end; i++) { // 左闭右闭区间
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) {
return false;
}
}
return true;
}
}
3.复杂度分析
时间复杂度:O(3^4).
空间复杂度:O(n).存疑?
LeetCode:78. 子集 - 力扣(LeetCode)
1.思路
子集怎么收集的过程似乎更重要,startIndex做标记,遇到节点就进行收集。
2.代码实现
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
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.remove(path.size() - 1);
}
}
}
3.复杂度分析
时间复杂度:O(n * 2^n).
空间复杂度:O(n).
LeetCode:
1.思路
续上一题,将数组进行树化,每个节点均为结果集中的一个元素,因存在相同数值,需要对结果进行去重,去重主要体现在树层去重,借助一个数组进行标记实现。
2.代码实现
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Boolean[] used;
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
used = new Boolean[nums.length];
// Arrays.fill(used, false);
backtracking(nums, used, 0);
return result;
}
private void backtracking(int[] nums, Boolean[] used, 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, used, i + 1);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
3.复杂度分析
时间复杂度:O(n * 2^n).
空间复杂度:O(n).