leetcode : Restore IP Addresses [回溯经典]???

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 {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<String>();
        if(s == null || s.length() < 4 || s.length() > 16) {
            return result;
        }
        
        helper(s, result, "", 0, 0);
        return result;
    }
    
    	public void helper(String s, List<String> res, String sb, int pos, int count) {
		
		if(pos >= s.length()) {
			return;
		}
		
		if(count == 3 && isValid(s.substring(pos, s.length()))) {
			res.add(sb + s.substring(pos, s.length()));
		}
		
		for(int i = pos; i<= pos + 3 && i<s.length(); i++) {
			String str = s.substring(pos, i + 1);
			if(isValid(str)) {
				helper(s, res, sb + str + ".",i + 1, count + 1);
			}
		}	
	}
	
	public boolean isValid(String str) {
	if(str==null || str.length()>3)  
        return false;  
    int num = Integer.parseInt(str);  
    if(str.charAt(0)=='0' && str.length()>1)  
        return false;  
    if(num>=0 && num<=255)  
        return true;  
    return false;  
	}
}

  

原文地址:https://www.cnblogs.com/superzhaochao/p/6562411.html