一、 93. 复原 IP 地址
题目连接:https://leetcode.cn/problems/restore-ip-addresses/
class Solution {
private List<String> result;
private List<String> paths;
private boolean isVail(String s) {
if (s.length() == 1) return true;
if (s.length() > 3) return false;
if (s.charAt(0) == '0') return false;
if (Integer.parseInt(s) > 255) return false;
return true;
}
private void backTracking(String s, int startIndex) {
if (paths.size() > 4) return;
if (startIndex >= s.length() && paths.size() == 4) {
//收集结果
StringBuilder str = new StringBuilder();
for (int i = 0; i < paths.size(); i++) {
str.append(paths.get(i));
if (i != paths.size() - 1) {
str.append(".");
}
}
result.add(str.toString());
return;
}
for (int i = startIndex; i < s.length(); i++){
String splitStr = s.substring(startIndex, i + 1);
if (!isVail(splitStr)) break;
paths.add(splitStr);
backTracking(s, i + 1);
paths.remove(paths.size() - 1);
}
}
public List<String> restoreIpAddresses(String s) {
result = new ArrayList<>();
paths = new ArrayList<>();
if (s.length() > 12) return result;
backTracking(s, 0);
return result;
}
}
二、 78. 子集
题目连接:https://leetcode.cn/problems/subsets/
class Solution {
private List<Integer> paths;
private List<List<Integer>> result;
private void backTracking(int[] nums, int indexStart){
result.add(new ArrayList<>(paths));
if (indexStart >= nums.length) return;
for (int i = indexStart; i < nums.length; i++){
paths.add(nums[i]);
backTracking(nums, i + 1);
paths.remove(paths.size() - 1);
}
}
public List<List<Integer>> subsets(int[] nums) {
paths = new ArrayList<>();
result = new ArrayList<>();
backTracking(nums, 0);
return result;
}
}
三、 90. 子集 II
题目连接:https://leetcode.cn/problems/subsets-ii/
class Solution {
private List<Integer> paths;
private List<List<Integer>> result;
private void backTacking(int[] nums, int startIndex, boolean[] uses) {
result.add(new ArrayList<>(paths));
if (startIndex >= nums.length) return;
for (int i = startIndex; i < nums.length; i++){
if (i > 0 && nums[i] == nums[i - 1] && !uses[i - 1]) continue;
paths.add(nums[i]);
uses[i] = true;
backTacking(nums, i + 1, uses);
uses[i] = false;
paths.remove(paths.size() - 1);
}
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
paths = new ArrayList<>();
result = new ArrayList<>();
Arrays.sort(nums);
boolean[] uses = new boolean[nums.length];
Arrays.fill(uses, false);
backTacking(nums, 0, uses);
return result;
}
}
网友评论