题目链接[93.复原IP地址])(https://leetcode.cn/problems/restore-ip-addresses/)
class Solution {
List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if(s.length() > 12) return res;
backTrack(s, 0, 0);
return res;
}
public void backTrack(String s, int startIndex, int pointNum){
if(pointNum == 3){
if(isValid(s, startIndex, s.length()-1))
res.add(s);
}
for(int i = startIndex; i < s.length(); i++){
if(isValid(s, startIndex, i)){
s = s.substring(0 ,i + 1) + "." + s.substring(i + 1);
pointNum++;
backTrack(s, i+2, pointNum);
pointNum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
}
}
}
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;
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums,0);
return res;
}
public void backTracking(int[] nums, int startIndex){
res.add(new ArrayList<>(path));
for(int i = startIndex; i< nums.length; i++){
path.add(nums[i]);
backTracking(nums, i + 1);
path.removeLast();
}
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backTracking(nums,0);
return res;
}
public void backTracking(int[] nums, int startIndex){
res.add(new ArrayList<>(path));
for(int i = startIndex; i< nums.length; i++){
if(i > startIndex && nums[i - 1] == nums[i]){
continue;
}
path.add(nums[i]);
backTracking(nums, i + 1);
path.removeLast();
}
}
}