回溯 分割问题框架
void dfs(string s, int start){
if(start >= s.size() && 中止条件){
result.push_back(path);
return;
}
for(int i=start; i<s.size(); i++){
string ss = s.substr(start, i-start+1);
if(judge(ss)){
path.push_back(ss);
dfs(s, i+1);
path.pop_back();
}
}
}
131. 分割回文串
- 分割问题与组合相同点 顺序拿, 不同在于组合可以不选。
- 当前字符串不是回文时不能break ef不是回文 efe是回文
- 截取字符串 s.substr(int start, int len)
class Solution {
public:
vector<vector<string>>result;
vector<string>path;
vector<vector<string>> partition(string s) {
dfs(s, 0);
return result;
}
bool judge(string s){
int start = 0;
int end = s.size()-1;
while(start <= end){
if(s[start++] != s[end--]) return false;
}
return true;
}
void dfs(string s, int start){
if(start >= s.size()){
result.push_back(path);
return;
}
for(int i=start; i<s.size(); i++){
string cur = s.substr(start, i-start+1);
if(!judge(cur)) continue;
path.push_back(cur);
dfs(s, i+1);
path.pop_back();
}
}
};
93. 复原 IP 地址
class Solution {
public:
vector<string>result;
string path;
int cnt = 0;
vector<string> restoreIpAddresses(string s) {
dfs(s, 0);
return result;
}
bool judge(string s){
if(s.size()>1 && s[0] == '0') return false;
if(s.size()>3 ) return false;
if(s.size() == 3 &&(s[0]>='3' ||(s[0]=='2' &&(s[1]>='6' || (s[1]=='5' && s[2]>='6'))))) return false;
return true;
}
void dfs(string s, int start){
if(start >= s.size() && cnt == 4){
result.push_back(path);
return;
}
if(cnt>=4 ||start >= s.size() ) return;
for(int i=start; i<s.size(); i++){
string cur = s.substr(start, i-start+1);
if(judge(cur)){
string temp = path;
if(cnt<3) path = path + cur +".";
else path = path + cur;
cnt++;
dfs(s, i+1);
path = temp;
cnt--;
}
}
}
};