LeetCode Restore IP Addresses

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> ips;
        vector<int> ip;
        dfs(s, 0, ip, ips);
        return ips;
    }
    
    void dfs(string& s, int pos, vector<int>& ip, vector<string>& ips) {
        int len = s.length();
        int fid = ip.size();
        if (len == pos) {
            if (fid == 4) {
                ips.push_back(intip2str(ip));
            }
            return;
        }
        
        if (3 * (4 - fid) < len - pos) return;  // avoid TL
        
        int cur = 0;
        for (int i=pos; i<len && i < pos+3; i++) {
            if (i != pos && cur == 0) break;   // no leading zero in ip addr
            cur = cur * 10 + s[i] - '0';
            if (cur > 255) break;
            ip.push_back(cur);
            dfs(s, i + 1, ip, ips);
            ip.pop_back();
        }
    }
    
    string intip2str(vector<int> &ip) {
        if (ip.size() != 4 ) {
            return "format error. number of fields should be 4";
        }
        string strip;
        for (int i=0; i<4; i++) {
            strip.append(to_string(ip[i]));
            strip.append(i==3 ? "" : ".");
        }
        return strip;
    } 
};

反正ip地址数字不过直接dfs,不过也要稍微剪枝一下,前导零不能使用

再写了一次,吐血了一个bug

class Solution {
private:
    vector<string> ips;
public:
    vector<string> restoreIpAddresses(string s) {
        vector<int> ip;
        dfs(s, 0, 0, ip);
        return ips;
    }
    
    void dfs(string& s, int pos, int part, vector<int>& ip) {
        int len = s.size();
        if (part == 4) {
            if (pos == len) {
                ips.push_back(int2ip(ip));
            }
            return;
        }
        int end = min(pos + 3, len);
        int v = 0;

        for (int i=pos; i<end; i++) {
            if (v == 0 && i - pos > 0) {
                break;
            }
            
            v = v * 10 + s[i] - '0';
            
            if (v <= 255 && (len - i) >= (3 - part)) {
                ip.push_back(v);
                dfs(s, i + 1, part + 1, ip);
                ip.pop_back();
            }
        }
    }
    
    string int2ip(vector<int>& ip) {
        char buf[16];
        sprintf(buf, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
        return buf;
    } 
};

 

posted @ 2014-07-05 08:55  卖程序的小歪  阅读(167)  评论(0编辑  收藏  举报