学习目标:
60天训练营打卡计划!
学习内容:
93.复原IP地址
- 题目有难度
- 首先是isIP函数,一定要确定好函数的结束条件。
- 对于backtracking函数,首先要明确其结束条件。
当插入的’ . '符号大于等于3时,要先判断第3个点后的字符是否是IP字符,是就添加到结果集。 - 对于backtracking函数,一定要卡好其范围,不能将’ . '符号传给isIP函数。
class Solution {
List<String> res = new ArrayList<>();
StringBuilder sb;
private boolean isIP(String s, int start, int end){
if(start >= s.length())
return false;
if(s.charAt(start) == '0' && start != end)
return false;
int sum = 0;
for(int i = start; i <= end; i++){
int tmp = s.charAt(i) - '0';
sum = sum * 10 + tmp;
if(sum > 255) return false;
}
return true;
}
private void backtracking(StringBuilder sb, int startIndex, int count){
if(count >= 3){
if(isIP(sb.toString(), startIndex, sb.length() - 1))
res.add(sb.toString());
return;
}
for(int i = startIndex; i < sb.length(); i++){
if(isIP(sb.toString(), startIndex, i)){
sb.insert(i + 1, '.');
backtracking(sb, i + 2, count + 1);
sb.deleteCharAt(i + 1);
}else{
break;
}
}
return;
}
public List<String> restoreIpAddresses(String s) {
sb = new StringBuilder(s);
backtracking(sb, 0, 0);
return res;
}
}
使用回溯进行分割的题目就做完了,题目特点是:
结果都在叶子节点处,都需要按题目的条件对其进行规范的判断。
78.子集
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> lis = new ArrayList<>();
private void backtracking(int[] nums, int startIndex){
res.add(new ArrayList<>(lis));
if(startIndex >= nums.length) return;
for(int i = startIndex; i < nums.length; i++){
lis.add(nums[i]);
backtracking(nums, i + 1);
lis.remove(lis.size() - 1);
}
return;
}
public List<List<Integer>> subsets(int[] nums) {
backtracking(nums, 0);
return res;
}
}
90.子集II
- 本题和昨天的40题基本逻辑都是一样的。
- 但是忘记怎么剪枝了。。。就当重新复习了一遍。。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> lis = new ArrayList<>();
int[] used;
private void backtracking(int[] nums, int[] used, int startIndex){
res.add(new ArrayList<>(lis));
if(startIndex >= nums.length) return;
for(int i = startIndex; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i-1] && used[i-1] != 1){
continue;
}
lis.add(nums[i]);
used[i] = 1;
backtracking(nums, used, i + 1);
used[i] = 0;
lis.remove(lis.size() - 1);
}
return;
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
used = new int[nums.length];
backtracking(nums, used, 0);
return res;
}
}
使用回溯求子集的题目就做完了,题目特点是:
结果在整棵树上,其他的和组合一模一样。
学习时间: