题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
#include <functional> class Solution { public: /** * * @param s string字符串 * @return string字符串vector */ vector<string> restoreIpAddresses(string s) { vector<string> res; function<void(int, int, string)> dfs = [&](int idx, int cnt, string path) -> void { if (cnt == 4 || idx == s.length()) { if (cnt == 4 && idx == s.length()) { path.pop_back(); res.push_back(path); } return; } string tmp; if (s[idx] == '0') { dfs(idx + 1, cnt + 1, path + "0."); return; } for (int i = idx; i < s.length(); ++i) { tmp += s[i]; if (stoi(tmp) > 255) break; dfs(i + 1, cnt + 1, path + tmp + "."); } }; dfs(0, 0, ""); return res; } };
思路:递归。
将每一段控制在255以内,递归即可。