93. Restore IP Addresses(dfs)

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)

思路:IP address的规则:一共四段;每段的值不能超过255;不能以0开头,但可以在一段中只有数字0

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        dfs(s, "", 1);
        return ret;
    }
    
    void dfs(string s, string currentIP, int depth){ //depth表示第几个section
        if(depth == 4){
            if(check(s)) 
                ret.push_back(currentIP+s);
            return;
        }
        
        int len = s.length();
        if(len < 5-depth){ //剩余string长度过短
            return;
        }
        
        string s1, s2;
        //check if we can assign 3 digits in the section
        if(len > 3 ){
            s1 = s.substr(0,3);
            
            if(check(s1)){
                s2 = s.substr(3);
                dfs(s2,currentIP+s1+".", depth+1);
            }
        }
        
        //check if we can assign 2 digits in the section
        if(len > 2 ){
            s1 = s.substr(0,2);
            if(check(s1)){
                s2 = s.substr(2);
                dfs(s2,currentIP+s1+".", depth+1);
            }
        }
        
        //assign 1 digits in the section
        s2 = s.substr(1);
        dfs(s2,currentIP+s[0]+".", depth+1);
    }
    
    bool check(string section){
        int len = section.length();
        if(len == 0 || len > 3) return false;
        int value = stoi(section);
        if(len==3){
            if(section[0]!='0' && value <= 255) return true;
            else return false;
        }
        else if(len==2){
            if(section[0]=='0') return false;
            else return true;
        }
        return true;
    }
private: 
    vector<string> ret;
};

 当然也能用循环,每两个section之间的分割用一个for循环遍历分割的位置,一共是三重for循环。

posted on 2015-10-05 09:51  joannae  阅读(232)  评论(0编辑  收藏  举报

导航