学习任务:
- Leetcode93. 复原 IP 地址
- Leetcode78. 子集
- Leetcode90. 子集 II
Leetcode93. 复原 IP 地址
难度:中等
| 相关标签:字符串、回溯
-
题目: 有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。
例如:“0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、“192.168.1.312” 和 “192.168@1.1” 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 ‘.’ 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。 -
思路:
-
注意:
- startIndex一定是需要的,因为不能重复分割,记录下一层递归分割的起始位置。
- 还需要一个变量pointNum,记录添加逗点的数量
- 判断子串是否合法
- 段位以0为开头的数字不合法
段位里有非正整数字符不合法
段位如果大于255了不合法
- 段位以0为开头的数字不合法
-
代码:
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;
}
// startIndex: 搜索的起始位置, pointNum:添加逗点的数量
public void backtracking(String s, int startIndex, int pointNum) {
if (pointNum == 3) {// 逗点数量为3时,分隔结束
// 判断第四段⼦字符串是否合法,如果合法就放进result中
if (isValid(s,startIndex,s.length()-1)) {
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex, i)) {
s = s.substring(0, i + 1) + "." + s.substring(i + 1); //在str的后⾯插⼊⼀个逗点
pointNum++;
backtracking(s, i + 2, pointNum);// 插⼊逗点之后下⼀个⼦串的起始位置为i+2
pointNum--;// 回溯
s = s.substring(0, i + 1) + s.substring(i + 2);// 回溯删掉逗点
} else {
break;
}
}
}
// 判断字符串s在左闭⼜闭区间[start, end]所组成的数字是否合法
public Boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) { // 如果⼤于255了不合法
return false;
}
}
return true;
}
}
- 反思:
Leetcode78. 子集
难度:中等
| 相关标签:位运算、数组、回溯
-
题目: 给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的
子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。 -
思路:
-
注意:
- 组合问题和分割问题都是收集树的叶子节点,而子集问题是找树的所有节点
-
代码:
class Solution {
List<Integer> path = new ArrayList<>();
List<List<Integer>> result = 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);
}
}
}
- 反思:
Leetcode90. 子集 II
难度:中等
| 相关标签:位运算、数组、回溯
-
题目: 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的
子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。 -
思路:
-
注意:
-
代码:
- 反思: