歡迎關註個人公眾號:愛喝可可牛奶 LeetCode演算法訓練 93.複原IP地址 78.子集 90.子集II LeetCode 93. 複原 IP 地址 分析 字元串全部由數字組成,ipv4每一段數字不能有前導0,且大小∈[0,255] 等價於將字元串進行分割,並判斷分割後的數是否滿足條件 插入一個點 ...
歡迎關註個人公眾號:愛喝可可牛奶
LeetCode演算法訓練 93.複原IP地址 78.子集 90.子集II
LeetCode 93. 複原 IP 地址
分析
字元串全部由數字組成,ipv4每一段數字不能有前導0,且大小∈[0,255]
等價於將字元串進行分割,並判斷分割後的數是否滿足條件
插入一個點進行切割、判斷是否滿足條件、再插入、再判斷,直到插入3個點,判斷剩下的一段是否滿足條件
代碼
class Solution {
List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) return res; // 算是剪枝了
backTrack(s, 0, 0);
return res;
}
// startIndex: 搜索的起始位置, pointNum:添加逗點的數量
private void backTrack(String s, int startIndex, int pointNum) {
if (pointNum == 3) {// 逗點數量為3時,分隔結束
// 判斷第四段⼦字元串是否合法,如果合法就放進res中
if (isValid(s,startIndex,s.length()-1)) {
res.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++;
backTrack(s, i + 2, pointNum);// 插⼊逗點之後下⼀個⼦串的起始位置為i+2
pointNum--;// 回溯
s = s.substring(0, i + 1) + s.substring(i + 2);// 回溯刪掉逗點
} else {
break;
}
}
}
// 判斷字元串s在左閉⼜閉區間[start, end]所組成的數字是否合法
private 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++) {
if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到⾮數字字元不合法
return false;
}
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) { // 如果⼤於255了不合法
return false;
}
}
return true;
}
}
LeetCode 78. 子集
分析
返回不含相同元素整數數組的子集
收集樹的每個節點
代碼
class Solution {
List<List<Integer>> result = new ArrayList<>();// 存放符合條件結果的集合
LinkedList<Integer> path = new LinkedList<>();// 用來存放符合條件結果
public List<List<Integer>> subsets(int[] nums) {
subsetsHelper(nums, 0);
return result;
}
private void subsetsHelper(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]);
subsetsHelper(nums, i + 1);
path.removeLast();
}
}
}
LeetCode 90. 子集 II
分析
返回含相同元素整數數組的子集 在前面基礎上去重
代碼
class Solution {
List<List<Integer>> result = new ArrayList<>();// 存放符合條件結果的集合
LinkedList<Integer> path = new LinkedList<>();// 用來存放符合條件結果
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
subsetsHelper(nums, 0);
return result;
}
private void subsetsHelper(int[] nums, int startIndex){
//「遍歷這個樹的時候,把所有節點都記錄下來,就是要求的子集集合」。
result.add(new ArrayList<>(path));
if (startIndex >= nums.length){ //終止條件可不加
return;
}
for (int i = startIndex; i < nums.length; i++){
// 註意這裡不是0
//if(i > 0 && nums[i] == nums[i-1]){
if(i > startIndex && nums[i] == nums[i-1]){
continue;
}
path.add(nums[i]);
subsetsHelper(nums, i + 1);
path.removeLast();
}
}
}
總結
- 涉及範圍確定,明確開閉區間
- 去重方式 Set去重、used數組去重、索引去重