文章目录
93.复原IP地址
文字讲解 :复原IP地址
视频讲解 :复原IP地址
**状态:**此题调试了几次ok,与昨天的分割回文子串相比,就是在判断终止条件处需要处理;
思路:
代码:
java
class Solution {
List<String> result = new ArrayList<>();
LinkedList<String> tempList = new LinkedList<>();
public List<String> restoreIpAddresses(String s) {
backTracking(0, s);
return result;
}
public void backTracking(Integer startIndex, String s) {
if (tempList.size() == 3) {
if (validIpParam(s.substring(startIndex, s.length()))) {
tempList.offer(s.substring(startIndex, s.length()));
result.add(getIp());
tempList.pollLast();
}
return;
}
for (int i = startIndex; i < s.length() && tempList.size()<=4; i++) {
if (validIpParam(s.substring(startIndex, i+1))) {
tempList.offer(s.substring(startIndex, i+1));
} else {
continue;
}
backTracking(i+1, s);
tempList.pollLast();
}
}
public boolean validIpParam(String s) {
if (s == null || s.length()==0) {
return false;
}
if (s.length()>=2 && s.charAt(0)=='0') {
return false;
}
if (s.length()>3) {
return false;
}
Integer num = Integer.valueOf(s);
if (num < 0 || num > 255) {
return false;
}
return true;
}
public String getIp() {
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < tempList.size(); i++) {
if (i==tempList.size()-1) {
resultStr.append(tempList.get(i));
} else {
resultStr.append(tempList.get(i)).append(".");
}
}
return resultStr.toString();
}
}
78.子集
文字讲解 :子集
视频讲解 :子集
状态:这一题的关键在于收集元素的位置,理解了回溯算法中的树形结构和理论知识,这题可以想到在for循环中收集元素即可
思路:
代码:
java
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> tempList = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums, 0);
result.add(new ArrayList<>());
return result;
}
public void backTracking(int[] nums, int index) {
if (index>=nums.length) {
return;
}
for (int i = index; i < nums.length; i++) {
tempList.add(nums[i]);
//收集元素
result.add(new ArrayList<>(tempList));
backTracking(nums, i+1);
tempList.pollLast();
}
}
}
90.子集II
文字讲解 :子集II
视频讲解 :子集II
状态:这题秒了
思路:
代码:
java
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> tempList = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
result.add(tempList);
//对数组先进行排序
Arrays.sort(nums);
backTracking(nums, 0);
return result;
}
public void backTracking(int[] nums, int startIndex) {
if (startIndex>=nums.length) {
return;
}
for (int i = startIndex; i < nums.length; i++) {
if (i>startIndex&&nums[i]==nums[i-1]) {
continue;
}
tempList.offer(nums[i]);
result.add(new ArrayList<>(tempList));
backTracking(nums, i+1);
tempList.pollLast();
}
}
}