[leetcode刷题系列]Restore IP Addresses

暴力dfs就好了


class Solution {
    bool isValid(string s){
        if(s.size() == 1)
            return true;
        if(s[0] == '0' || s.size() > 3)
            return false;
        int ret = 0;
        for(int i = 0; i < s.size(); ++ i)
            ret = ret * 10 + s[i] - '0';
        return ret <= 255;
            
    }
    vector<string> dfs(string s, int num){
        vector<string> vs;
        if(num == 1){
            if(isValid(s))
                vs.push_back(s);
            return vs;
        }
        for(int i = 0; i < 3 && i + 1 < s.size(); ++ i){
            string now = s.substr(0, i + 1);
            if(isValid(now)){
                vector<string> ret = dfs(s.substr(i + 1, s.size() - i - 1), num - 1);
                for(int j = 0; j < ret.size(); ++ j)
                    vs.push_back(now + '.' + ret[j]);
            }
        }
        return vs;
    }
public:
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return dfs(s, 4);
    }
};


你可能感兴趣的:([leetcode刷题系列]Restore IP Addresses)