1、leetcode93 复原IP地址
class Solution {
List<String> res = new ArrayList<>();
public boolean isValid(String s, int start, int end) {
if(start > end) {
return false;
}
if(s.charAt(start) == '0' && start != end) {
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) {
return false;
}
}
return true;
}
public void backTracking(String s, int startIndex, int pointNum) {
if(pointNum == 3) {
if (isValid(s,startIndex,s.length()-1)) {
res.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); //在str的后⾯插⼊⼀个逗点
pointNum++;
backTracking(s, i + 2, pointNum);// 插⼊逗点之后下⼀个⼦串的起始位置为i+2
pointNum--;// 回溯
s = s.substring(0, i + 1) + s.substring(i + 2);// 回溯删掉逗点
} else {
break;
}
}
}
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) return res; // 算是剪枝了
backTracking(s, 0, 0);
return res;
}
}
2、leetcode78 子集
class Solution {
List<Integer> path = new LinkedList<Integer>();
List<List<Integer>> res = new ArrayList<>();
public void backTracking(int[] nums, int startIndex) {
res.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.remove(path.size()-1);
}
}
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums, 0);
return res;
}
}
3、leetcode90 子集Ⅱ
class Solution {
List<Integer> path = new LinkedList<Integer>();
List<List<Integer>> res = new ArrayList<>();
public void backTracking(int[] nums, int startIndex) {
res.add(new ArrayList<>(path));
if(startIndex >= nums.length) {
return;
}
for(int i=startIndex; i<nums.length; i++) {
if(i > startIndex && nums[i] == nums[i - 1]) {
continue;
}
path.add(nums[i]);
backTracking(nums, i+1);
path.remove(path.size()-1);
}
}
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backTracking(nums, 0);
return res;
}
}
标签:return,nums,int,res,day27,startIndex,new
From: https://www.cnblogs.com/hzj-bolg/p/17121132.html