代码随想录算法训练营第二十八天| 93.复原IP地址、78.子集、90.子集II
93.复原IP地址
题目链接
文章讲解
class Solution {
public:
vector<string> ans;
bool isVaild(const string& s, const int& begin, const int& end) {
if (begin > end) return false;
if (s[begin] == '0' && begin != end) return false;
int sum = 0;
for (int i = begin; i <= end; i++) {
sum = sum * 10 + s[i] - '0';
if (sum > 255) return false;
}
return true;
}
void backtracking(string& s, int idx, int pointNum) {
if (pointNum == 3) {
if (isVaild(s, idx, s.size() - 1))
ans.push_back(s);
return;
}
for (int i = idx; i < s.size() && isVaild(s, idx, i); i++) {
s.insert(s.begin() + i + 1, '.');
backtracking(s, i + 2, pointNum + 1);
s.erase(s.begin() + i + 1);
}
}
vector<string> restoreIpAddresses(string s) {
if (s.size() < 4 || s.size() > 12) return ans;
backtracking(s, 0, 0);
return ans;
}
};
78.子集
题目链接
文章讲解
class Solution {
public:
vector<vector<int>> ans = {{}};
vector<int> path;
void backtracking(const vector<int>& nums, int start) {
for (int i = start; i < nums.size(); i++) {
path.push_back(nums[i]);
ans.push_back(path);
if (i + 1 < nums.size()) backtracking(nums, i + 1);
path.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
backtracking(nums, 0);
return ans;
}
};
90.子集II
题目链接
文章讲解
class Solution {
public:
vector<int> path;
vector<vector<int>> ans;
void backtracking(const vector<int>& nums, int start) {
ans.push_back(path);
for (int i = start; i < nums.size(); i++) {
if (i > start && nums[i] == nums[i - 1]) continue;
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return ans;
}
};