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)
Solution1:Brute Force
思路:循环列举出所有的可能性并check是否valid
Note:Brute Force: systematically enumerating all possible candidates for the solution and checking whether each candidate satisfies the problem's statement.
Time Complexity: O(3^4) Space Complexity: O(1) 不算结果
Solution2:回溯(DFS)写法
思路: backtrack出每一种组合,并check if valid。(这里采用建立tmp string, so no remove here;或用同一内存的string +后再remove也可以。两种具体写法方式)
另外,CodeChange: String改用StringBuilder更好
Note:其实DFS也是一种Brute Force,只不过写法上更specific,含有path depth概念
Time Complexity: O(3^4) Space Complexity: O(1) 不算结果
Solution1 Code:
class Solution1 {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
int len = s.length();
for(int i = 1; i<4 && i<len-2; i++){
for(int j = i+1; j<i+4 && j<len-1; j++){
for(int k = j+1; k<j+4 && k<len; k++){
String s1 = s.substring(0,i), s2 = s.substring(i,j), s3 = s.substring(j,k), s4 = s.substring(k,len);
if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)){
res.add(s1+"."+s2+"."+s3+"."+s4);
}
}
}
}
return res;
}
public boolean isValid(String s){
if(s.length()>3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s)>255)
return false;
return true;
}
}
Solution2 Code:
class Solution2 {
public List<String> restoreIpAddresses(String s) {
List<String> solutions = new ArrayList<String>();
restoreIp(s, solutions, 0, "", 0);
return solutions;
}
private void restoreIp(String ip, List<String> solutions, int idx, String restored, int count) {
if (count > 4) return;
if (count == 4 && idx == ip.length()) solutions.add(restored);
for (int i=1; i<4; i++) {
if (idx+i > ip.length()) break;
String s = ip.substring(idx,idx+i);
if ((s.startsWith("0") && s.length()>1) || (i==3 && Integer.parseInt(s) >= 256)) continue;
restoreIp(ip, solutions, idx+i, restored+s+(count==3?"" : "."), count+1);
}
}
}