题目1:【二刷完成】
class Solution {
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
backTracking(s,0,0);
return result;
}
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);
pointNum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
}else{
break;
}
}
}
boolean isValid(String s, int startIndex, int end){
if (end<startIndex) return false;
if (s.charAt(startIndex)=='0' && startIndex!=end) return false;
int num = 0;
for (int i=startIndex;i<=end;i++){
if (s.charAt(i)>'9' || s.charAt(i)<'0') return false;
num = num*10 + (s.charAt(i)-'0');
if (num>255) return false;
}
return true;
}
}
题目2:【二刷完成】
class Solution {
List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
public List<List<Integer>> subsets(int[] nums) {
subsetsHelper(nums, 0);
return result;
}
private void subsetsHelper(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]);
subsetsHelper(nums, i + 1);
path.removeLast();
}
}
}
题目3:【二刷完成】
lass Solution {
List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
boolean[] used;
public List<List<Integer>> subsetsWithDup(int[] nums) {
if (nums.length == 0){
result.add(path);
return result;
}
Arrays.sort(nums);
used = new boolean[nums.length];
subsetsWithDupHelper(nums, 0);
return result;
}
private void subsetsWithDupHelper(int[] nums, int startIndex){
result.add(new ArrayList<>(path));
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;
}
path.add(nums[i]);
used[i] = true;
subsetsWithDupHelper(nums, i + 1);
path.removeLast();
used[i] = false;
}
}
}