93.复原IP地址
有效 IP 地址 正好由四个整数(每个整数位于 0
到 255
之间组成,且不能含有前导 0
),整数之间用 '.'
分隔。
- 例如:
"0.1.2.201"
和"192.168.1.1"
是 有效 IP 地址,但是"0.011.255.245"
、"192.168.1.312"
和"192.168@1.1"
是 无效 IP 地址。
给定一个只包含数字的字符串 s
,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s
中插入 '.'
来形成。你 不能 重新排序或删除 s
中的任何数字。你可以按 任何 顺序返回答案。
示例 1:
输入:s = "25525511135" 输出:["255.255.11.135","255.255.111.35"]
class Solution {
List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
backtracking(s, 0, 0);
return res;
}
public void backtracking(String s, int index, int count){
if(count == 3){
if(isValid(s, index, s.length()-1)){
res.add(s);
}
return;
}
for(int i = index; i < s.length(); i++){
if(isValid(s, index, i)){
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
count++;
backtracking(s, i + 2, count);
s = s.substring(0, i + 1) + s.substring(i + 2);
count--;
}else{
break;
}
}
}
public boolean isValid(String s, int start, int end){
if(start > end) return false;
if(s.charAt(start) == '0' && start != end) return false;
if(Long.parseLong(s.substring(start, end+1)) > 255 ) return false;
return true;
}
}
78.子集
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3] 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
backtracking(nums, 0);
return res;
}
public void backtracking(int[] nums, int index){
res.add(new ArrayList<>(path));
if(index >= nums.length){
return;
}
for(int i = index; i < nums.length; i++){
path.add(nums[i]);
backtracking(nums, i+1);
path.removeLast();
}
}
}
90.子集II
给你一个整数数组 nums
,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2] 输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
bcaktrackint(nums, 0);
return res;
}
public void bcaktrackint(int[] nums, int index){
res.add(new ArrayList<>(path));
if(index >= nums.length){
return;
}
for(int i = index; i < nums.length; i++){
if ( i > index && nums[i - 1] == nums[i] ) {
continue;
}
path.add(nums[i]);
bcaktrackint(nums, i+1);
path.removeLast();
}
}
}