您的位置:首页 > 其它

leetcode 93. Restore IP Addresses

2016-04-26 22:24 429 查看
发现我不会上图啊。。。这样我就不加题目描述了。反正题目已经写清题号了,你们去leetcode按图索驹就是了。就是个典型的回溯法,主要麻烦在各种情况的处理上了。话说回溯法和字符串处理结合的题套路还满固定,要诀主要在递归函数的设计,设计的不合理了就会很麻烦。我恰每次都要忙活半天。。还是要练啊。下面是代码:
public class Solution {
List<String> out=null;
public List<String> restoreIpAddresses(String s) {
out=new ArrayList<String>();
if(s.length()<4)return out;
String str="";
help(s,0,str,1);
return out;

}
void help(String s,int head,String str,int count){
for(int i=head+1;i<=Math.min(head+3,s.length()+1);i++){
int num=Integer.parseInt(s.substring(head,i));
if(s.charAt(head)=='0'&&num!=0)return;//0.03.illegal
if(num==0&&i-head>1)return;//0.00.illegal
if(num<256){
String o=str+num;
if(count==4){
if(i!=s.length())continue;//0.0.0.0 0illegal
out.add(o);
return;
}else {
o+=".";
if(s.length()-i<4-count)return;
help(s,i,o,count+1);
}

}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 回溯法