提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
一、力扣93. 复原 IP 地址
class Solution {
List<String> res = new ArrayList<>();
StringBuilder sb;
public List<String> restoreIpAddresses(String s) {
StringBuilder sb = new StringBuilder(s);
fun(sb, 0, 0);
return res;
}
public void fun(StringBuilder s, int start, int depth){
if(depth == 3){
if(flag(s, start, s.length()-1)){
res.add(s.toString());
}
return;
}
for(int i = start; i < s.length(); i ++){
if(flag(s, start, i)){
s.insert(i+1, '.');
fun(s, i+2, depth+1);
s.deleteCharAt(i+1);
}else{
break;
}
}
}
public boolean flag(StringBuilder s, int start, int end){
if(start > end)
return false;
if(s.charAt(start) == '0' && start != end)
return false;
int num = 0;
for(int i = start; i <= end; i++){
int digit = s.charAt(i) - '0';
num = num * 10 + digit;
if(num > 255)
return false;
}
return true;
}
}
二、力扣78. 子集
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
res.add(new ArrayList<>(path));
fun(nums, 0);
return res;
}
public void fun(int[] nums, int start){
for(int i = start; i < nums.length; i ++){
path.add(nums[i]);
res.add(new ArrayList<>(path));
fun(nums, i+1);
path.remove(path.size()-1);
}
}
}
三、力扣90. 子集 II
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums){
Arrays.sort(nums);
fun(nums, 0);
return res;
}
public void fun(int[] nums, int start){
res.add(new ArrayList<>(path));
if(start == nums.length){
return ;
}
for(int i = start; i < nums.length; i ++){
if(i > start && nums[i] == nums[i-1]){
continue;
}
path.add(nums[i]);
fun(nums, i+1);
path.remove(path.size()-1);
}
}
}