原题网址:https://leetcode.com/problems/restore-ip-addresses/
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)
方法:深度优先搜索。
public class Solution {
/*
"0000"
"00000"
"25525511135"
"9245587303"
"0279245587303"
"010010"
*/
private void find(String s, int[] pos, int step, List<String> addresses) {
if (step == pos.length-1) {
if (pos[step]-pos[step-1]>3) return;
if (pos[step]-pos[step-1]>1 && s.charAt(pos[step-1]) == '0') return;
int a = Integer.parseInt(s.substring(pos[step-1]), 10);
if (a>255) return;
StringBuilder sb = new StringBuilder();
for(int i=0; i<pos.length-1; i++) {
if (i>0) sb.append(".");
sb.append(s.substring(pos[i], pos[i+1]));
}
addresses.add(sb.toString());
return;
}
// Set<Integer> used = new HashSet<>();
for(int i=pos[step-1]+1; i+(3-step)<pos[pos.length-1]; i++) {
int a = Integer.parseInt(s.substring(pos[step-1], i), 10);
if (a>255) break;
// if (used.contains(a)) continue;
// used.add(a);
pos[step] = i;
find(s, pos, step+1, addresses);
if (a==0) break;
}
}
public List<String> restoreIpAddresses(String s) {
List<String> addresses = new ArrayList<>();
int[] pos = new int[5];
pos[0] = 0;
pos[4] = s.length();
find(s, pos, 1, addresses);
return addresses;
}
}