93. Restore IP Addresses
第一次用了新的string记录,但在原始的string上分割就可以了
class Solution {
public:
vector<string> res;
void findIP(string& s, int startIndex, int count){
if(count ==3){
if(isValid(s, startIndex, s.size()-1)){
res.push_back(s);
}
return;
}
for(int i=startIndex; i<s.size() ; i++){
if(isValid(s, startIndex, i)){
s.insert(s.begin()+i+1, '.');
findIP(s, i+2, count+1);
s.erase(s.begin()+i+1);
}else{
return;
}
}
}
bool isValid(const string& s, int start, int end){
if(start > end){
return false;
}
if(s[start] == '0' && start != end){
return false;
}
int num = 0;
for(int i=start; i<=end; i++){
if(s[i] > '9' || s[i] < '0') return false;
num = num*10+(s[i]-'0');
if(num > 255) return false;
}
return true;
}
vector<string> restoreIpAddresses(string s) {
findIP(s, 0, 0);
return res;
}
};
78. Subsets
class Solution {
public:
vector<vector<int>> res;
vector<int> set;
void findSet(vector<int>& nums,int startIndex){
res.push_back(set);
for(int i=startIndex; i<nums.size(); i++){
set.push_back(nums[i]);
findSet(nums,i+1);
set.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
findSet(nums, 0);
return res;
}
};
90. Subsets II
class Solution {
public:
vector<vector<int>> res;
vector<int> set;
void findSet(vector<int>& nums, int startIndex, vector<bool>& used){
res.push_back(set);
for(int i=startIndex; i<nums.size(); i++){
if(i>0 && nums[i] == nums[i-1] && used[i-1] == false){
continue;
}
set.push_back(nums[i]);
used[i] = true;
findSet(nums, i+1, used);
set.pop_back();
used[i] = false;
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
findSet(nums, 0, used);
return res;
}
};