【leetcode】Restore IP Addresses (middle)

时间:2023-12-21 13:20:08

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)

思路:回溯法 解向量X={str0, str1, str2, str3} 分别是IP地址的四段

判断每个解向量的部分时,先求出该部分最长和最短长度(根据后面每段最少1位,最多3位),回溯求解。符合条件时就把X按照要求的格式压入ans.

注意,判断每个部分是否有效时要排除00,01,001...等0开头的情况。

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std; class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
int len = s.length();
if(len < )
return ans; vector<string> X(, "");
vector<vector<string>> S(, vector<string>());
int k = ;
int maxlen = min(, len - * );
int minlen = max(, len - * );
for(int i = minlen; i <= maxlen; i++)
{
string sub = s.substr(, i);
if(isVaildIP(sub))
{
S[].push_back(sub);
}
} while(k >= )
{
while(!S[k].empty())
{
X[k] = S[k].back();
S[k].pop_back();
if(k < )
{
k = k + ;
int startloc = ;
for(int j = ; j < k; j++)
{
startloc += X[j].length();
}
int maxlen = min(, len - ( - k - ) * - startloc);
int minlen = max(, len - ( - k - ) * - startloc);
for(int i = minlen; i <= maxlen; i++)
{
string sub = s.substr(startloc, i);
if(isVaildIP(sub))
{
S[k].push_back(sub);
}
}
}
else
{
ans.push_back(X[]);
for(int i = ; i < ; i++)
{
ans.back().append(".");
ans.back().append(X[i]);
}
}
}
k--;
} return ans;
} bool isVaildIP(string snum)
{
if(snum.size() > && snum[] == '')
return false;
int num = atoi(snum.c_str());
return (num >= && num <= );
}
}; int main()
{
Solution s;
string num =/* "25525511135"*/"";
vector<string> ans = s.restoreIpAddresses(num); return ;
}