LeetCode刷题 Day28
93. Restore IP Addresses
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.
- For example,
"0.1.2.201"and"192.168.1.1"are valid IP addresses, but"0.011.255.245","192.168.1.312"and"192.168@1.1"are invalid IP addresses.
Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
Example 1:
Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000"
Output: ["0.0.0.0"]
Example 3:
Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
思路:
- 这个和分割回文串的题目是一样的,区别在于判断valid IP 和返回条件
代码:
var restoreIpAddresses = function(s) {
let res = [];
const helper = function(path, startIndex) {
if (startIndex > s.length - 1 ) {
console.log(path.length, path)
if (path.length === 4) {
res.push(path.join("."));
}
}
for (let i = startIndex; i < s.length; i++) {
let str = s.substring(startIndex, i + 1);
if (isValidAddr(str)) {
path.push(str);
helper(path, i + 1);
path.pop();
}
}
}
var isValidAddr = function(s) {
if (s.length > 1 && s.charAt(0) === '0') return false;
else if (parseInt(s) > 255 || parseInt(s) < 0) return false
else return true;
}
helper([], 0);
return res;
};
78. Subsets
Given an integer array nums of unique elements, return all possible
subsets (the power set) .
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
思路:
- 子集可以理解为没有长度限制的组合,就无需添加限制条件,直接将path添加到result数组里
- 无需终止条件,因为当startIndex >= nums.length的时候,for循环就结束了
代码:
var subsets = function(nums) {
let res = [];
const helper = function(path, startIndex) {
res.push([...path]);
for (let i = startIndex; i < nums.length; i++) {
path.push(nums[i]);
helper(path, i + 1);
path.pop();
}
}
helper([], 0);
return res;
};
90. Subsets II
Given an integer array nums that may contain duplicates, return all possible
subsets (the power set) .
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,2]
Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
思路:
- 类似于有重复数字的组合的题目,但是子集没有长度限制,关键依然在于如何去重
- 排序
if (i > startIndex && nums[i] === nums[i - 1]) continue;
代码:
var subsetsWithDup = function(nums) {
let res = [];
nums.sort((a, b) => a - b);
const helper = function(path, startIndex) {
res.push([...path]);
for (let i = startIndex; i < nums.length; i++) {
if (i > startIndex && nums[i] === nums[i - 1]) continue;
path.push(nums[i]);
helper(path, i + 1);
path.pop();
}
}
helper([], 0);
return res;
};