[LeetCode]46. Restore IP Addresses复原IP地址
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)
Subscribe to see which companies asked this question
解法1:暴力破解法。三层循环确定前面三个数字,最后剩下的所有作为第四个数字。实际每层循环最多执行三遍。循环中使用作为正确IP地址的条件进行剪枝。需要注意考虑各种边界条件。
class Solution { public: vector<string> restoreIpAddresses(string s) { int n = s.size(); string addr = ""; vector<string> res; for (int i = 0; i < n - 3 && i < 3; ++i) { string fir(s.begin(), s.begin() + i + 1); if ((fir[0] != '0' || fir.size() == 1) && stoi(fir) <= 255) { for (int j = i + 1; j < n - 2 && j < i + 4; ++j) { string sec(s.begin() + i + 1, s.begin() + j + 1); if ((sec[0] != '0' || sec.size() == 1) && stoi(sec) <= 255) { for (int k = j + 1; k < n - 1 && k < j + 4; ++k) { string trd(s.begin() + j + 1, s.begin() + k + 1); if ((trd[0] != '0' || trd.size() == 1) && stoi(trd) <= 255) { string fth(s.begin() + k + 1, s.end()); if ((fth[0] != '0' || fth.size() == 1) && fth.size() < 4 && stoi(fth) <= 255) { addr += fir + '.' + sec + '.' + trd + '.' + fth; res.push_back(addr); addr.clear(); } } } } } } } return res; } };