题目来源:https://leetcode.com/problems/restore-ip-addresses/
问题描述
93. Restore IP Addresses
Medium
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
------------------------------------------------------------
题意
给出一个由纯数字组成的字符串,分割该字符串使之成为合法的ip地址,求所有可能的ip地址
------------------------------------------------------------
思路
深搜剪枝。搜索的时候要注意遇到‘0’开头的字符串只能是‘0’,不能是‘01’或者‘012’之类的。剪枝的话我就简单加了位数的剪枝,比如当前还有两段ip但是只剩下1个数字或者剩下超过2*3=6个数字了,就剪枝。
------------------------------------------------------------
代码
class Solution {
List<String> ret = new LinkedList<String>();
public List<String> restoreIpAddresses(String s) {
dfs(s, "", 0, 0);
return this.ret;
}
public void dfs(String s, String ip, int ind, int cnt)
{
int len = s.length();
if (cnt == 4)
{
if (ind == len) {
this.ret.add(ip);
}
return;
}
if (len-ind < 4-cnt || len-ind > 3*(4-cnt)) // 剪枝
{
return;
}
if (s.charAt(ind) == '0') // 以0开头的两位以上数字是不合法的
{
if (cnt < 3) {
dfs(s, ip + "0.", ind+1, cnt+1);
} else {
dfs(s, ip + "0", ind+1, 4);
}
return;
}
String tmp;
for (int i=1; i<=3 && ind+i<=len; i++)
{
tmp = s.substring(ind, ind+i);
Integer num = Integer.parseInt(tmp);
if (num < 256) {
if (cnt < 3) {
dfs(s, ip + tmp + ".", ind+i, cnt+1);
} else {
dfs(s, ip + tmp, ind+i, 4);
}
}
}
}
}