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 中的任何数字。你可以按 任何 顺序返回答案。
使用回溯法对所有可能的情况进行遍历:结束条件为正好用完所有字符且所有字符以ip格式有3个逗号分隔,每次递归判断当前组合是否有效,即是否位于0到255之间且除0外不以0作为开头。代码如下:
class Solution {
private:
vector<string> _res;
string _path;
bool isValid(string& s, int start, int end) {
if (end - start + 1 > 3) return false;
if (s[start] == '0' && start != end) return false;
int num = 0;
for (int i = start; i <= end; ++i) {
num = num * 10 + s[i] - '0';
if (num > 255) return false;
}
return true;
}
void backtrack(string& s, int start, int count) {
if (start == s.length()) {
if (count == 4) {
_res.push_back(_path);
}
return;
}
for (int i = start; i < s.length(); ++i) {
if (isValid(s, start, i)) {
int len = _path.length();
_path += s.substr(start, i - start + 1);
if (count < 3) {
_path += ".";
}
backtrack(s, i + 1, count + 1);
_path.erase(len);
} else break;
}
}
public:
vector<string> restoreIpAddresses(string s) {
if (s.length() < 4 || s.length() > 12) return _res;
backtrack(s, 0, 0);
return _res;
}
};
78.子集
题目描述:
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
与经典回溯法思路相同,对于终止条件的判断,仅当起始位置start到达数组末尾即遍历完所有元素时返回,且在判断终止条件前将当前_path计入结果(避免遗漏含有数组最后一个元素的子集)。代码如下:
class Solution {
private:
vector<vector<int>> _res;
vector<int> _path;
void backtrack(vector<int>& nums, int start) {
_res.push_back(_path);
if (start == nums.size()) return;
for (int i = start; i < nums.size(); ++i) {
_path.push_back(nums[i]);
backtrack(nums, i + 1);
_path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
backtrack(nums, 0);
return _res;
}
};
90.子集II
题目描述:
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
思路同上题&40.组合总和II,对数组排序后进行去重操作,对于每次迭代的当前层,若当前值与前一个索引对应值相同则只记录每一层起始位置的值,防止结果遗漏以及由于在同一层选择相同元素导致的重复。代码如下:
class Solution {
private:
vector<vector<int>> _res;
vector<int> _path;
void backtrack(vector<int>& nums, int start) {
_res.push_back(_path);
if (start == nums.size()) return;
for (int i = start; i < nums.size(); ++i) {
if (i > start && nums[i] == nums[i - 1]) continue;
_path.push_back(nums[i]);
backtrack(nums, i + 1);
_path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
backtrack(nums, 0);
return _res;
}
};