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 pointSum){
if(pointSum==3){
if(isvaild(s,startIndex,s.length()-1)){
result.add(s);
}
return;
}
for(int i = startIndex;i<s.length();i++){
if(isvaild(s,startIndex,i)){
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
pointSum++;
backTracking(s,i+2,pointSum);
s = s.substring(0, i + 1) + s.substring(i + 2);
pointSum--;
}else{
break;
}
}
}
// 判断字符串s在左闭?闭区间[start, end]所组成的数字是否合法
private Boolean isvaild(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;
}
}
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backTracking(nums,0);
return result;
}
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();
}
}
}
40.组合总和II?和?78.子集?,本题就是这两道题目的结合
秒了,简单
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backTracking(nums,0);
return result;
}
void backTracking(int [] nums,int startIndex){
result.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.removeLast();
}
}
}