题目:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
Subscribe to see which companies asked this question
查找一个字符串构成的所有合法ip
代码:
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
List<String> ip = new ArrayList<String>();
dfs(res,ip,0,s);
return res;
}
void dfs(List<String> res,List<String> ip,int start,String s)
{
if(start==s.length()&&ip.size()==4 )
{
String temp = "";
temp=ip.get(0)+"."+ip.get(1)+"."+ip.get(2)+"."+ip.get(3);
res.add(temp);
return;
}
if(s.length()-start < (4-ip.size()))return ;
if(s.length()-start >(4-ip.size())*3)return ;
int num=0;
for(int i= start;i<start+3;i++)
{
if(i>s.length()-1)break;
num=num*10+(s.charAt(i)-'0');
if(num<0 || num>255)continue;
ip.add(""+num);
dfs(res,ip,i+1,s);
ip.remove(ip.size()-1);
if(num ==0)break;
}
}
}