原题地址:https://leetcode-cn.com/problems/restore-ip-addresses/description/
题目描述:
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
解题方案:
又是一道回溯法的题目,自己还是不能很会解决回溯算法的题目,遇到稍微麻烦的题目就不知该怎么下手了,要多加练习呀。。
暴力尝试1个字符、2个字符、3个字符。。
本题用到了string()函数,之前没有遇到过这种用法,学到了!!
class Solution {
public:
vector<string> ans;
void dfs(string &s, int index, int num, string tmp) {
if ((5 - num) * 3 < s.size() - index)
return;
if (num == 5) {
ans.push_back(tmp);
return;
}
if (s[index] == '0')
dfs(s, index + 1, num + 1, tmp + (num == 1 ? "0" : ".0"));
else {
for (int i = 1; i < 4 && i + index <= s.size(); ++ i)
if (i < 3 || string(s, index, i) <= "255")
dfs(s, index + i, num + 1, tmp + (num == 1 ? "" : ".") + string(s, index, i));
}
}
vector<string> restoreIpAddresses(string s) {
dfs(s, 0, 1, "");
return ans;
}
};