93.复原IP地址
93. 复原 IP 地址 - 力扣(LeetCode)
class Solution {
public:
bool validNumber(string sNumber){ // “判断是否合格”
if(stoi(sNumber) <= 255){
return true;
}
return false;
}
vector<string> paths;
void restoreIpAddresses(string s, int start, string path, int depth){
if(start >= s.size() && depth == 4){
paths.push_back(path); // 符合要求
}
if(depth > 4){
return;
}
if(path != ""){
path += '.';
}
string tempPath;
for(int i = start; i < s.size() && i < start + 3; i++){
if(s[start] == '0'){ // 前导0
path += '0';
restoreIpAddresses(s, start + 1, path, depth + 1);
break;
}
tempPath += s[i];
if(validNumber(tempPath)){
int pathSize = path.size();
path += tempPath;
restoreIpAddresses(s, i + 1, path, depth + 1);
path.resize(pathSize); // 回溯
}else{
break;
}
}
}
vector<string> restoreIpAddresses(string s) {
string path;
restoreIpAddresses(s, 0, path, 0);
return paths;
}
};
78.子集
78. 子集 - 力扣(LeetCode)
class Solution {
public:
vector<vector<int>> results;
void subsets(vector<int>& nums, int start, vector<int> &path){
results.push_back(path);
if(start >= nums.size()){
return ;
}
for(int i = start; i < nums.size(); i++){
path.push_back(nums[i]);
subsets(nums, i + 1, path);
path.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> path;
subsets(nums, 0, path);
return results;
}
};
90.子集II
90. 子集 II - 力扣(LeetCode)
class Solution {
public:
vector<vector<int>> results;
void subsets(vector<int>& nums, int start, vector<int> &path){
results.push_back(path);
if(start >= nums.size()){
return ;
}
for(int i = start; i < nums.size(); i++){
path.push_back(nums[i]);
subsets(nums, i + 1, path);
while(i < nums.size() - 1 && nums[i] == nums[i + 1]){
i++;
}
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> path;
subsets(nums, 0, path);
return results;
}
};