93. 复原 IP 地址 - 力扣(LeetCode)
class Solution {
ArrayList<String> results = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if(s.length() > 12){
return new ArrayList<>();
}
char[] ipChars = s.toCharArray();
doRestoreIpAddresses(ipChars,0,"",4);
return results;
}
public void doRestoreIpAddresses(char[] ipChars,int startPos,String oneResult,int remainCount){
if(startPos == ipChars.length && remainCount == 0){
results.add(oneResult.replaceFirst(".",""));
return;
}
for(int i=startPos;i<ipChars.length;i++){
if(remainCount < 0 || i-startPos >= 3){
return;
}
//截取当前
String nowSubString = new String(ipChars,startPos,i-startPos+1);
if(Integer.parseInt(nowSubString) > 255 || (nowSubString.startsWith("0") && nowSubString.length()>=2)){
return;
}
oneResult = oneResult + '.' + nowSubString;
doRestoreIpAddresses(ipChars,i+1,oneResult,--remainCount);
//不截取当前
remainCount++;
oneResult = oneResult.substring(0,oneResult.lastIndexOf("."));
}
}
}
78. 子集 - 力扣(LeetCode)
class Solution {
public List<List<Integer>> subsets(int[] nums) {
if(nums.length == 0){
return new ArrayList<>();
}
ArrayList<Integer> oneResult = new ArrayList<>();
ArrayList<List<Integer>> results = new ArrayList<>();
doSubSets(nums,0,oneResult,results);
return results;
}
private void doSubSets(int[] nums,int startPos,ArrayList<Integer> oneResult, List<List<Integer>> results){
results.add(new ArrayList<>(oneResult));
for(int i=startPos;i<nums.length;i++){
oneResult.add(nums[i]);
doSubSets(nums,i+1,oneResult,results);
oneResult.remove(oneResult.size()-1);
}
}
}
90. 子集 II - 力扣(LeetCode)
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
if(nums.length == 0){
return new ArrayList<>();
}
Arrays.sort(nums);
ArrayList<Integer> oneResult = new ArrayList<>();
ArrayList<List<Integer>> results = new ArrayList<>();
doSubsetsWithDup(nums,0,oneResult,results);
return results;
}
public void doSubsetsWithDup(int[] nums,int startPos,ArrayList<Integer> oneResult,ArrayList<List<Integer>> results) {
results.add(new ArrayList<>(oneResult));
for(int i=startPos;i<nums.length;i++){
if(i>startPos && nums[i] == nums[i-1]){
continue;
}
oneResult.add(nums[i]);
doSubsetsWithDup(nums,i+1,oneResult,results);
oneResult.remove(oneResult.size()-1);
}
}
}