Day 28 回溯 Part04
今日任务
- 93.复原IP地址
- 78.子集
- 90.子集II
代码实现
今天的题出乎意料的简单
复原IP地址,和昨天的分割回文串比较像
一个是分割,一个是判断ip有效
List<String> result = new ArrayList<>();List<String> path = new ArrayList<>();public List<String> restoreIpAddresses(String s) {if (s.length() < 4 || s.length() > 12) {return result;}backtracking(s, 0);return result;}void backtracking(String s, Integer startIndex) {if (path.size() == 4) {if (startIndex == s.length()) {result.add(String.join(".", path));}return;}for (int i = startIndex; i < s.length() && i < startIndex + 3; i++) {String substring = s.substring(startIndex, i + 1);if (substring.length() > 1 && substring.charAt(0) == '0') {return;}if (Integer.parseInt(substring) > 255) {return;}int remainLength = s.substring(i).length();if (remainLength < 4 - path.size() || remainLength > 3 * (4 - path.size())) {return;}path.add(substring);backtracking(s, i + 1);path.remove(path.size() - 1);}}
子集问题,完完全全的模板
List<List<Integer>> res = new ArrayList<>();List<Integer> path1 = new ArrayList<>();public List<List<Integer>> subsets(int[] nums) {backtracking(nums, 0);return res;}void backtracking(int[] nums, int startIndex) {res.add(new ArrayList<>(path1));if (startIndex >= nums.length) {return;}for (int i = startIndex; i < nums.length; i++) {path1.add(nums[i]);backtracking(nums, i + 1);path1.remove(path1.size() - 1);}}
子集II,比子集多了一个去重,然后去重是昨天做过的
public List<List<Integer>> subsetsWithDup(int[] nums) {Arrays.sort(nums);boolean[] used = new boolean[nums.length];backtracking(nums, 0, used);return res;}void backtracking(int[] nums, int startIndex, boolean[] used) {res.add(new ArrayList<>(path1));if (startIndex >= nums.length) {return;}for (int i = startIndex; i < nums.length; i++) {if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {continue;}path1.add(nums[i]);used[i] = true;backtracking(nums, i + 1, used);path1.remove(path1.size() - 1);used[i] = false;}}
今日总结
- 今天的题相当之简单,并且都是在昨天的基础上,以至于我看了提示都能写出来
- 跑路跑路
- 今天又绿了,蒙了一个是运气,第二个没蒙对是实力
明天预计又是低开,高不高走呢?