28-1.93复原IP地址
题目
思路
回溯法
代码
class Solution {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) return result;
backTracking(s, 0, 0);
return result;
}
private void backTracking(String s, int startIndex, int pointNum) {
if (pointNum == 3) {
if (isValid(s, startIndex, s.length()-1)) {
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex,i)) {
s = s.substring(0, i+1) + "." + s.substring(i+1);
pointNum++;
backTracking(s, i+2, pointNum); // 插⼊逗点之后下⼀个⼦串的起始位置为i+2
pointNum--;
s = s.substring(0, i+1) + s.substring(i+2);
}else{
break;
}
}
}
private Boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到⾮数字字符不合法
return false;
}
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) { // 如果⼤于255了不合法
return false;
}
}
return true;
}
}
28-2.78子集
题目
思路
回溯法
代码
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums, 0);
return result;
}
private void backTracking(int[] nums, int startIndex) {
result.add(new ArrayList<>(path));
if (startIndex >= nums.length) {
return;
}
for (int i = startIndex; i < nums.length; i++) {
path.add(nums[i]);
backTracking(nums, i+1);
path.removeLast();
}
}
}
28-3.90子集II
题目
思路
回溯法
代码
//不使用used数组
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backTracking(nums, 0);
return result;
}
private void backTracking(int[] nums, int start) {
result.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i-1] == nums[i]) {
continue;
}
path.add(nums[i]);
backTracking(nums, i+1);
path.removeLast();
}
}
}