给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
方法一:
class Solution {
public:vector<string> restoreIpAddresses(string s) {vector<string> res;helper(s, 0, "", res);return res;}void helper(string s, int n, string out, vector<string>& res) {if (n == 4) {if (s.empty()) res.push_back(out);} else {for (int k = 1; k < 4; ++k) {if (s.size() < k) break;int val = atoi(s.substr(0, k).c_str());if (val > 255 || k != std::to_string(val).size()) continue;helper(s.substr(k), n + 1, out + s.substr(0, k) + (n == 3 ? "" : "."), res);}}}
};