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
思路:循環(huán)列舉出所有的可能性并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) 不算結(jié)果
Solution2:回溯(DFS)寫法
思路: backtrack出每一種組合钮惠,并check if valid规肴。(這里采用建立tmp string, so no remove here缺猛;或用同一內(nèi)存的string +后再remove也可以中姜。兩種具體寫法方式)
另外,CodeChange: String改用StringBuilder更好
Note:其實(shí)DFS也是一種Brute Force薯演,只不過寫法上更specific撞芍,含有path depth概念
Time Complexity: O(3^4) Space Complexity: O(1) 不算結(jié)果
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);
}
}
}