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)
总结一点,要求出所有组合的问题,一般用dfs;如果要求总数,用dp。
public class Solution {
public boolean isValid(String s){
if(s.charAt(0) == '0') return s.equals("0");
int num = Integer.parseInt(s);
return num > 0 && num < 256;
}
public void dfs(String s1, String s2, ArrayList<String> res, int count){//分成前后两部分进行深度优先搜索
if(count == 3 && isValid(s1)){
res.add(s2 + s1);
return ;
}
for(int i=1; i<4 && i<s1.length(); i++){
String str2 = s1.substring(0, i);
if(isValid(str2)){
String str1 = s1.substring(i);
dfs(str1, s2+str2+".", res, count+1);
}
}
}
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> res = new ArrayList<String>();
if(s == null) return res;
int len = s.length();
if(len <4 || len >12 ) return res;
dfs(s, "", res, 0);
return res;
}
}