题目:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]. (Order does not matter)
题意:
给定一个字符串,将它划分为IP地址的格式。
思路:
这是一道明显的回溯的题目。一个IP地址可以分为四个位置,每个位置的数字的位数理论可能性是1位,2位或者3位。但是需要判断这个数字能否作为该位置上的数。
- 首先需要满足如果位数超过一位,那么第一位不能是0。
- 如果是三位的数字,那么该数字不能比255大。
- 剩余的字符要能够满足接下来的那些位置。比如剩余k个字符,还有m个位置没有填充,那么k<=3*m && k >= m,就是说k最小要能够满足每一位上可以放一个数,k最大不能超过每一位放三个数字。
以上。
代码如下:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
if(s == "")return vector<string>();
vector<string> result;
vector<string> temp;
backTracking(s,0,result,temp,1);
return result;
}
void backTracking(string s,int start,vector<string>& result,vector<string>& temp,int count){
if(count == 4){
if(s.size() - start > 1 && (s.substr(start))[0] == '0')return;
else if(s.size() - start > 3)return;
else if(s.size() - start == 3 && (s.substr(start)) > "255")return;
string ss = temp[0] + temp[1] + temp[2] + s.substr(start);
result.push_back(ss);
cout<<ss<<endl;
return;
}
else if(count == 4)return;
for(int i = 1; i <= 3; i++){
if(s.size() - start- i > (4 - count)*3)continue;
else if(s.size() - start - i < (4-count))break;
string stemp = s.substr(start,i);
if(i > 1 && stemp[0] == '0')continue;
if(i == 3 && stemp > "255")continue;
temp.push_back(stemp+".");
backTracking(s,start + i,result,temp,count + 1);
temp.pop_back();
}
}
};