今日任务
93.复原IP地址
- 题目链接: https://leetcode.cn/problems/restore-ip-addresses/description/
- 题目描述:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/dd687cb8a2a74a729138b93c7a1dcae2.png)
Code
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
vector<string> path;
int n = s.size();
if(n > 12 || n < 4){
return {};
}
function<void(int)> dfs = [&](int i)->void{
if(i == n && path.size() == 4){
ans.emplace_back(path[0] + "." + path[1] + "." + path[2] + "." + path[3]);
return;
}
for(int j = i; j < n; j++){
string t = s.substr(i, j - i + 1);
if(t.size() > 3){
return;
}
int tNum = stoi(t);
if(to_string(tNum) != t){
return;
}
if(path.size() < 4 && tNum >= 0 && tNum <= 255){
path.push_back(t);
dfs(j + 1);
path.pop_back();
}
}
};
dfs(0);
return ans;
}
};
78.子集
- 题目链接: https://leetcode.cn/problems/subsets/description/
- 题目描述:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/3218e24f92cc432b952e740b59df314e.png)
Code
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
vector<int> path;
function<void(int)> dfs = [&](int i)->void{
ans.emplace_back(path);
if(i == n){
return;
}
for(int j = i; j < n; j++){
path.push_back(nums[j]);
dfs(j + 1);
path.pop_back();
}
};
dfs(0);
return ans;
}
};
90.子集II
- 题目链接:https://leetcode.cn/problems/subsets-ii/description/
- 题目描述:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/a476b6da8e154dab8ead75c0a9b3954b.png)
Code
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
ranges::sort(nums);
vector<vector<int>> ans;
vector<int> path;
int n = nums.size();
function<void(int)> dfs = [&](int i)->void{
ans.emplace_back(path);
if(i == n){
return;
}
for(int j = i; j < n; j++){
if(j == i || j > i && nums[j] != nums[j - 1]){
path.push_back(nums[j]);
dfs(j + 1);
path.pop_back();
}
}
};
dfs(0);
return ans;
}
};