93. 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)

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 restoreIpAddresses(String s) {
        List res = new ArrayList();
        int len = s.length();
        for(int i = 1; i<4 && i3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s)>255)
            return false;
        return true;
    }
}

Solution2 Code:

class Solution2 {
    public List restoreIpAddresses(String s) {
        List solutions = new ArrayList();
        restoreIp(s, solutions, 0, "", 0);
        return solutions;
    }

    private void restoreIp(String ip, List 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);
        }
    }
}

你可能感兴趣的:(93. Restore IP Addresses)