URL
https://leetcode.com/problems/restore-ip-addresses/description/
描述:
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)
思路
深度优先搜索,注意剪枝的时候合法IP的判断条件。
代码示例
//全局变量存贮结果
private List<String> result = new ArrayList<String>();
//s 输入字符串
// n部分,Ip 有四个部分
// index 起始位置
// cur 临时结果,一次深度搜索的临时结果
private void dfs(String s,int n,int index,String cur){
//找到四部分但是还有剩余字符串,该情况直接返回
if(n==4 && index != s.length()){
return;
}
//找到了四部分,正好使用全部字符,将结果保存
if(n==4 && index==s.length()) {
this.result.add(cur);
return;
}
//dfs 重点部分,从当前位置使用1-3个字符,如果符合IP规则,则进行下一步的DFS,否则终止循环。(注意数组边界)
for(int i=1;i<4;i++){
if(index+i>s.length()) break;
String temp = s.substring(index,index+i);
if(temp.startsWith("0")&&temp.length()>1 || Integer.valueOf(temp)>255){
break;
}
String tempCur = cur+temp;
if(n!=3) tempCur+=".";
dfs(s,n+1,index+i,tempCur);
}
}
public List<String> restoreIpAddresses(String s) {
this.result.clear();
dfs(s,0,0,"");
return result;
}