47. 全排列 II
class Solution {List<List<Integer>> result = new ArrayList<>();List<Integer> path = new ArrayList<Integer>();public List<List<Integer>> permuteUnique(int[] nums) {Arrays.sort(nums);boolean[] used = new boolean[nums.length];permuteUnique(nums, used);return result;}private void permuteUnique(int[] nums, boolean[] used) {if (path.size() == nums.length) {result.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) {continue;}if (used[i] == true) {continue;}used[i] = true;path.add(nums[i]);permuteUnique(nums, used);used[i] = false;path.remove(path.size() - 1);}}
}
93. 复原 IP 地址
class Solution {List<String> result = new ArrayList<>();public List<String> restoreIpAddresses(String s) {int pointSum = 0;StringBuilder sb = new StringBuilder(s);restoreIpAddresses(sb, 0, pointSum);return result;}private void restoreIpAddresses(StringBuilder s, int startIndex, int pointSum) {if (pointSum == 3) {String substring = s.substring(startIndex);if (valid(substring)) {result.add(s.toString());}return;}for (int i = startIndex; i < s.length(); i++) {String str = s.substring(startIndex, i);boolean valid = valid(str);if (!valid) {continue;}s.insert(i, ".");pointSum = pointSum + 1;restoreIpAddresses(s, i + 1, pointSum);pointSum = pointSum - 1;s.deleteCharAt(i);}}private boolean valid(String str) {if (str.length() == 0 || str.length() > 3) {return false;}if (str.length() > 1 && str.startsWith("0")) {return false;}int i;try {i = Integer.parseInt(str);} catch (NumberFormatException e) {return false;}if (i >= 0 && i <= 255) {return true;}return false;}}