Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]
解法1:暴力搜索
把字符串分为4段,每一段的长度小于4,大于0,遍历四个长度,当四个长度和为字符串的大小时,保存。
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
for(int a=1;a<4;a++){
for(int b=1;b<4;b++){
for(int c=1;c<4;c++){
for(int d=1;d<4;d++){
if(a+b+c+d == s.size()){
int n1 = stoi(s.substr(0,a));
int n2 = stoi(s.substr(a,b));
int n3 = stoi(s.substr(a+b,c));
int n4 = stoi(s.substr(a+b+c,d));
if(n1<=255 && n2<=255 && n3<=255 && n4<=255){
string t = to_string(n1)+"."+to_string(n2)+"."+to_string(n3)+"."+to_string(n4);
if(t.size() == s.size()+3)
res.push_back(t);
}
}
}
}
}
}
return res;
}
};
解法2:递归
定义一个数表示递归的段数,可以从4到0,也可以从0到4,并判断字符串是否合法。
从0->4
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
helper(s, 0, "",res);
return res;
}
void helper(string s, int k, string out, vector<string>& res){
if(k == 4){
if(s.empty())
res.push_back(out);
}
else{
for(int i=1;i<=3;i++){
if(s.size() < i) break;
int val = stoi(s.substr(0,i));
if(val > 255 || to_string(val).size() != i)
continue;
if(k==3)
helper(s.substr(i), k+1, out+s.substr(0,i),res);
else
helper(s.substr(i), k+1, out+s.substr(0,i)+".",res);
}
}
}
};
4->0
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
helper(s, 4, "",res);
return res;
}
void helper(string s, int k, string out, vector<string>& res){
if(k == 0){
if(s.empty())
res.push_back(out);
}
else{
for(int i=1;i<=3;i++){
if(s.size()>=i && isValid(s.substr(0,i))){
if(k==1)
helper(s.substr(i), k-1, out+s.substr(0,i),res);
else
helper(s.substr(i), k-1, out+s.substr(0,i)+".",res);
}
}
}
}
bool isValid(string s){
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
int res = stoi(s);
return res <= 255 && res >= 0;
}
};