2014年5月9日星期五

Recursive Solution - Restore IP Addresses

Recursive solution - find the head + recursive call (remaining)… separate the digit == 1 case since that is the end of recursion… Always find the end condition for recursion, versus sub problems for DP.

public class Solution {
    public ArrayList<String> restoreIpAddresses(String s) {
        if(s == null || s.length() < 4 || s.length() > 12){
            return new ArrayList<String>();
        }
        return restoreIPOps(s, 4);
    }
   
    private ArrayList<String> restoreIPOps(String s, int digit){
        ArrayList<String> res = new ArrayList<String>();
        if(digit <= 0 || s == null || s.length() < digit || s.length() > 3 * digit){
            return res;
        }
        if(digit == 1){
            if(isValidIP(s)){
                res.add(s);
                return res; //return
            }else{
                return res;
            }
        }
        int size = Math.min(3, s.length());
        while(size > 0){
            if(isValidIP(s.substring(0, size))){
                ArrayList<String> temp = restoreIPOps((size == s.length() ? null : s.substring(size, s.length())), digit - 1);
                if(!temp.isEmpty()){
                    for(String cur : temp){
                        res.add(s.substring(0, size) + "." + cur);
                    }
                }
            }
            size--;
        }
        return res;
    }
   
    private boolean isValidIP(String s){
        if(Integer.parseInt(s) > 255 || Integer.parseInt(s) < 0 || (s.charAt(0) == '0' && s.length() > 1)){
            return false;
        }
        return true;
    }
}

没有评论: