题目链接:93.复原IP地址
文档链接:93.复原IP地址
视频链接:回溯算法如何分割字符串并判断是合法IP?| LeetCode:93.复原IP地址
class Solution {
private:
vector<string> result;
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] < '0' || s[i] > '9'){
return false;
}
num = num * 10 + (s[i]-'0');
if(num > 255){
return false;
}
}
return true;
}
void backtracking(string& s, int startIdx, int pointNum){
if(pointNum == 3){
if(isValid(s, startIdx, s.size()-1)){
result.push_back(s);
}
return;
}
for(int i = startIdx; i<s.size();i++){
if(isValid(s,startIdx, i)){
s.insert(s.begin()+i+1,'.');
pointNum++;
backtracking(s, i+2, pointNum);
pointNum--;
s.erase(s.begin()+i+1);
}
else break;
}
return;
}
public:
vector<string> restoreIpAddresses(string s) {
result.clear();
if(s.size()<4||s.size()>12) return result;
backtracking(s, 0, 0);
return result;
}
};
题目链接:78.子集
文档链接:78.子集
视频链接:回溯算法解决子集问题,树上节点都是目标集和! | LeetCode:78.子集
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIdx){
result.push_back(path);
if(startIdx >= nums.size()) return;
for(int i = startIdx; i<nums.size(); i++){
path.push_back(nums[i]);
backtracking(nums, i+1);
path.pop_back();
}
return;
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};
题目链接:90.子集II
文档链接:90.子集II
视频链接:回溯算法解决子集问题,如何去重?| LeetCode:90.子集II
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIdx, vector<bool> used){
result.push_back(path);
if(startIdx>=nums.size()) return;
for(int i = startIdx; i<nums.size(); i++){
if(i>0 && nums[i]==nums[i-1] && used[i-1] == 0) continue;
path.push_back(nums[i]);
used[i] = true;
backtracking(nums, i+1, used);
used[i] = false;
path.pop_back();
}
return;
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end());
vector<bool> used(nums.size(), false);
backtracking(nums, 0, used);
return result;
}
};