首页 > 代码库 > 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)

解:

主要思想:採用递归的方式。一个一个的增加到最后的ip中

void formIpAddr(vector<string>&ret, string curIp, string nums, int idxIp){
        if(idxIp==1){
            if(nums.size()>3 || (nums.size()>1&&nums[0]==‘0‘)){
                return ;
            }
            const char * data=http://www.mamicode.com/nums.c_str();".";
                formIpAddr(ret, tmp, nums.substr(1), idxIp-1);
                return;
            }
            else{
                int i;
                string tmp;
                for(i=0; i<2 && i+idxIp<=nums.size(); i++){
                    tmp=nums.substr(0, i+1);
                    formIpAddr(ret, curIp+tmp+".", nums.substr(i+1), idxIp-1);
                }
                if(i+idxIp<=nums.size()){
                    const char * data=http://www.mamicode.com/nums.substr(0,i+1).c_str();".", nums.substr(i+1), idxIp-1);
                }
            }
        }
        
    }

    vector<string> restoreIpAddresses(string s) {
        vector<string> ret;
        if(s.size()<4)
            return ret;
        string curIp="";
        
        formIpAddr(ret, curIp, s, 4);
        return ret;
    }




Restore IP Addresses