93. Restore IP Addresses
二刷。
忘了一刷怎么做的,回头看很乱,也是类似于BackTrack的方法。
二刷做起来很清晰。
一个IP地址包含4个部分,每个部分可能有1、2 或者 3位。
1位可以是0-9
2位可以是1-99
3位可以是1-255
2 3位的情况下,它们的首位不能是0,比如010的值是10(assuming we cast and compare int..instead of Strings....),也是不合理的,需要注意。。。
应该有一些可以提前停止的情况,比如剩下的位数<没构建的部分数 之类的。。
public class Solution {
public List<String> restoreIpAddresses(String s)
{
List<String> res = new ArrayList<>();
if(s.length() == 0) return res;
List<String> tempList = new ArrayList<String>();
helper(res,tempList,s,0);
return res;
}
public void helper(List<String> res, List<String> tempList, String s, int m)
{
if( tempList.size() == 4)
{
if(m == s.length())
{
res.add(tempList.get(0) + "." + tempList.get(1) + "." + tempList.get(2) + "." + tempList.get(3));
}
return;
}
else
{
//1
if(s.length()-m < 4-tempList.size()) return;
if(m < s.length() && s.charAt(m) >= '0' && s.charAt(m) <= '9')
{
//System.out.println("here?");
tempList.add(s.substring(m,m+1));
helper(res,new ArrayList<>(tempList),s,m+1);
tempList.remove(tempList.size()-1);
}
//2
if(s.charAt(m)!= '0')
if(m < s.length() - 1 &&Integer.valueOf(s.substring(m,m+2)) > 0 && Integer.valueOf(s.substring(m,m+2)) <= 99)
{
tempList.add(s.substring(m,m+2));
helper(res,new ArrayList<>(tempList),s,m+2);
tempList.remove(tempList.size()-1);
}
//3
if(s.charAt(m)!= '0')
if(m < s.length() - 2 && Integer.valueOf(s.substring(m,m+3)) > 0 && Integer.valueOf(s.substring(m,m+3)) <= 255)
{
tempList.add(s.substring(m,m+3));
helper(res,new ArrayList<>(tempList),s,m+3);
tempList.remove(tempList.size()-1);
}
return;
}
}
}
写完考虑了一下怎么处理重复的情况。
考虑了几分钟找到办法,抽了自己2巴掌。怎么可能有重复的情况……
三刷。
DFS+剪枝。
总共有4个数,每次可以选1、2、3位,就是brach.
然后剪枝条件比较多,首先保证确实是1 2 3 位数,比如03不是两位数,取两位得是10-99,三位是100-255
再比如,剩下的位数也有要求,比如还剩2个数没添加,但是只剩一位了,吃了屎也组不出来;剩下10位,还有3个数没添加,也组不出来。
简而言之,剩的位数 >= 没组的数, <= 没组的数的3倍。
然后没了。。
Time: someone says cannot define in bigO notation..but looks like O(n^4)..
space: O(n)
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
if (s.length() == 0) return res;
dfs(res, s, 0, "");
return res;
}
public void dfs(List<String> res, String s, int m, String tempS) {
if (s.length() == 0) {
if (m == 4) {
res.add(tempS.substring(1));
return;
}
} else {
// 1 digit
if (s.length() - 1 >= 4 - m - 1 && s.length() - 1 <= (4 - m - 1) * 3) {
dfs(res, s.substring(1), m + 1, tempS + "." + s.substring(0,1));
}
// 2 digits
if (s.length() >= 2 && s.length() - 2 >= 4 - m - 1 && s.length() - 2 <= (4 - m - 1) * 3) {
if (Integer.valueOf(s.substring(0,2)) >= 10) {
dfs(res, s.substring(2), m + 1, tempS + "." + s.substring(0,2));
}
}
// 3 digits
if (s.length() >= 3 && s.length() - 3 >= 4 - m - 1 && s.length() - 3 <= (4 - m - 1) * 3) {
if (Integer.valueOf(s.substring(0,3)) >= 100 && Integer.valueOf(s.substring(0,3)) <= 255) {
dfs(res, s.substring(3), m + 1, tempS + "." + s.substring(0,3));
}
}
}
}
}

浙公网安备 33010602011771号