93.复原IP地址
cpp
class Solution {
private:
vector<string> res;
string temp;
void backtracing(string& s, int startIndex, int cnt) {
if (cnt > 4) { // 是否是四位整数
return;
}
if (cnt == 4 && startIndex >= s.size()) {
res.push_back(temp.substr(0, temp.size() - 1)); // 去掉最后一个'.'
return;
}
for (int i = startIndex; i < s.size(); ++i) {
string str = s.substr(startIndex, i - startIndex + 1); // 切割子串
if (str.size() >= 4) { // 防止转换为数字的时候溢出
continue;
}
int num = stoi(str);
if ((str.size() == 1 || (str.size() > 1 && str[0] != '0')) && (num >= 0 && num <= 255)) { // 不含前导零,且范围在[0,255]之间
temp += str;
temp.push_back('.');
} else {
continue;
}
backtracing(s, i + 1, cnt + 1);
temp.pop_back(); // 回溯 去'.'
temp = temp.substr(0, temp.size() - str.size()); // 去str
}
}
public:
vector<string> restoreIpAddresses(string s) {
res.clear();
temp.clear();
backtracing(s, 0, 0);
return res;
}
};
78.子集
收集树中的所有节点
cpp
class Solution {
private:
vector<vector<int>> res;
vector<int> temp;
void backtracing(vector<int>& nums, int startIndex) {
res.push_back(temp);
for (int i = startIndex; i < nums.size(); ++i) {
temp.push_back(nums[i]);
backtracing(nums, i + 1);
temp.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
backtracing(nums, 0);
return res;
}
};
90.子集II
cpp
class Solution {
private:
vector<vector<int>> res;
vector<int> temp;
void backtracing(vector<int>& nums, vector<bool>& used, int startIndex) {
res.push_back(temp);
for (int i = startIndex; i < nums.size(); ++i) {
if (i > 0 && used[i - 1] == false && nums[i] == nums[i - 1]) {
continue;
}
used[i] = true;
temp.push_back(nums[i]);
backtracing(nums, used, i + 1);
used[i] = false;
temp.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<bool> used(nums.size(), false);
backtracing(nums, used, 0);
return res;
}
};