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)
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> ans;
if (s == "" || s.length() > 12)
{
return ans;
}
string vS[4];
RestoreIPDFS(ans, vS, 0, s, 0);
return ans;
}
void RestoreIPDFS(vector<string> &ans, string vS[], int count, string &s, int step)
{
if (count == 4)
{
if (step == s.length())
{
string str = vS[0];
for (int i = 1; i < 4; ++i)
{
str += '.';
str += vS[i];
}
ans.push_back(str);
}
return;
}
// 如果當前s中剩餘的長度爲[4-count, 3*(4-count)]則可以
int remain = s.length() - step;
if ((remain >= (4 - count)) && (remain <= (12 - 3 * count)))
{// 此次解析i個字符
for (int i = 1; i <= min(3, remain); ++i)
{
string tmp = s.substr(step, i);
// 如果長度不爲0,則第一個不能爲0
if (i > 1 && tmp[0] == '0')
{
continue;
}
if (atoi(tmp.c_str()) <= 255)
{
vS[count] = tmp;
RestoreIPDFS(ans, vS, count + 1, s, step + i);
}
}
}
}
};