93.复原IP地址
class Solution {
public:
vector<string>ans;
void backtrace(string& s,int cnt,int index,string& str){
if(cnt==4 || index==s.size() ){
if(cnt==4 && index==s.size())
ans.push_back(str.substr(0,str.size()-1));
return;
}
for(int i=1;i<=3;i++){
if(index+i>s.size()) return;
if(s[index]=='0' && i!=1) return;
if(i==3 && s.substr(index,i)>"255") return;
str+=s.substr(index,i);
str.push_back('.');
backtrace(s,cnt+1,index+i,str);
str = str.substr(0,str.size()-i-1);
}
}
vector<string> restoreIpAddresses(string s) {
string str ="";
backtrace(s,0,0,str);
return ans;
}
};
78.子集
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex) {
result.push_back(path);
if (startIndex >= nums.size()) {
return;
}
for (int i = startIndex; i < nums.size(); i++) {
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};
90.子集2
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex, vector<bool>& used) {
result.push_back(path);
for (int i = startIndex; i < nums.size(); i++) {
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
continue;
}
path.push_back(nums[i]);
used[i] = true;
backtracking(nums, i + 1, used);
used[i] = false;
path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<bool> used(nums.size(), false);
backtracking(nums, 0, used);
return result;
}
};