原题链接:https://leetcode-cn.com/problems/restore-ip-addresses/
题目描述
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。
例如:“0.1.2.201” 和 “192.168.1.1” 是 有效的 IP 地址,但是 “0.011.255.245”、“192.168.1.312” 和 “192.168@1.1” 是 无效的 IP 地址。
示例 1:
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]
示例 2:
输入:s = “0000”
输出:[“0.0.0.0”]
示例 3:
输入:s = “1111”
输出:[“1.1.1.1”]
示例 4:
输入:s = “010010”
输出:[“0.10.0.10”,“0.100.1.0”]
题解
搜索顺序:依次搜索每一个数,每个数有多种选择方案。
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
vector<string> res;
vector<string> restoreIpAddresses(string s)
{
string path = "";
dfs(s, 0, path, 0);
return res;
}
void dfs(string s, int start, string path, int k)
{
if(start == s.size())
{
if(k == 4){
res.push_back(path.substr(1));
}
return;
}
if(k > 4) return;
if(k == 3&& start < s.size() -3) return;
if(s[start] == '0')
{
dfs(s, start + 1, path + ".0", k + 1);
}
else
{
for(int i = start, t = 0; i < s.size(); i++)
{
t = t * 10 + s[i] - '0';
if(t < 256) dfs(s, i + 1, path + "." + to_string(t), k + 1);
else break;
}
}
}