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)

 

class Solution {
public:
    vector<string> ans;
    vector<string> restoreIpAddresses(string s) {
        ans.clear();
        vector<string> path;
        dfs(s,path,0);
        return ans; 
    }
    bool isOk(string s, int start, int end){
        int sum = 0;
        int b = 1;
        //比如0XX 0X 都不允许
        if (s[start] == '0' && end - start > 1){
            return false;
        }        
        for(int i = end -1; i >= start; i--){
            sum +=  (s[i] - '0')*b;
            b *= 10;
        }
        if (sum >= 0 && sum < 256){
            return true;
        }
        return false;
    }
    void dfs(string s, vector<string> & path, int pos){
        if (path.size() == 4){
            if (pos >= s.size()){
                string one = path[0];
                for(int i = 1; i < path.size(); i++){
                    one += ".";
                    one += path[i];
                }
                ans.push_back(one);
                return;
            }
        }
        for(int i = 1; i < 4; i++){
            if (pos + i <= s.size() && isOk(s,pos,pos+i)){
                //剩下的长度过长
                int left = s.size() - pos - i;
                if (path.size() + left/3.0 > 4){
                    continue;
                }
                path.resize(path.size() +1);
                path[path.size() -1] = s.substr(pos,i);
                dfs(s,path,pos+i);
                path.resize(path.size() -1);
            }
        }
    }
};

using namespace std;
int main(int argc, char *argv[]) {
    string s = "010010";
    Solution sol;
    vector<string> ans = sol.restoreIpAddresses(s);
    for(int i = 0; i < ans.size(); i++){
        cout << ans[i] << endl;
    }
}

 

posted @ 2013-06-29 11:33  一只会思考的猪  阅读(223)  评论(0编辑  收藏  举报