标签:
花了差不多一个晚上找bug,将
string tmpString;
tmpString += s[start + 0] + s[start + 1] + s[start + 2];
改为
string tmpString;
tmpString.push_back(s[start + 0]);tmpString.push_back(s[start + 1]);tmpString.push_back(s[start + 2]);
程序就正常了,什么原因!!!
class Solution {
public:
void backtracking(string s, int start, int depth, vector<string> &result, string &output, int length) {
if(start >= length)
return;
if(depth == 3) {
if(length - start > 3)
return;
if(length - start == 1) {
output.push_back(s[start]);
result.push_back(output);
output.pop_back();
return;
}
if( length - start == 2) {
if(s[start] != ‘0‘) {
output.push_back(s[start]);output.push_back(s[start + 1]);
result.push_back(output);
output.pop_back();output.pop_back();
return;
}else {
return;
}
}
if( length - start == 3) {
if(s[start] != ‘0‘) {
string tmpString;
tmpString.push_back(s[start + 0]);tmpString.push_back(s[start + 1]);tmpString.push_back(s[start + 2]);
int tmpInt = stoi(tmpString);
if(tmpInt > 255) {
return;
}else {
output.push_back(s[start]);output.push_back(s[start + 1]);output.push_back(s[start + 2]);
result.push_back(output);
output.pop_back();output.pop_back();output.pop_back();
return;
}
}else {
return;
}
}
}
output.push_back(s[start + 0]);output.push_back(‘.‘);
backtracking(s, start + 1, depth + 1, result, output, length);
output.pop_back();output.pop_back();
if((s[start] != ‘0‘) && (length - start >= 2)) {
output.push_back(s[start + 0]); output.push_back(s[start + 1]);output.push_back(‘.‘);
backtracking(s, start + 2, depth + 1, result, output, length);
output.pop_back(); output.pop_back();output.pop_back();
}
if((s[start] != ‘0‘) && (length - start >= 3)) {
string tmpString;
tmpString.push_back(s[start + 0]);tmpString.push_back(s[start + 1]);tmpString.push_back(s[start + 2]);
int tmpInt = stoi(tmpString);
if(tmpInt > 255) {
return;
}else {
output.push_back(s[start + 0]);output.push_back(s[start + 1]);output.push_back(s[start + 2]);output.push_back(‘.‘);
backtracking(s, start + 3, depth + 1, result, output, length);
output.pop_back();output.pop_back();output.pop_back();output.pop_back();
}
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> result;
string output;
int length = s.size();
backtracking(s, 0, 0, result, output, length);
return result;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode(93) Restore IP Addresses
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/47283129