leetcode[93]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:

bool valid(string num)

{

    if(num.size()==1)return (num>="0"&&num<="9");

    if(num.size()==2)return (num>="10"&&num<="99");

    if(num.size()==3)return (num>="100"&&num<="255");

    return false;

}

void find(vector<string> &res, vector<string> &ips, int kth, int begin,string &s)

{

    if (begin==s.size())

    {

        if(kth==5)

        {

            string tmp=ips[0];

            for (int i=1;i<ips.size();i++)

            {

                tmp+=('.'+ips[i]);

            }

            res.push_back(tmp);

            return;

        }

        return;

    }

    for (int k=1;k<4&&(begin+k-1<s.size());k++)

    {

        string ip=s.substr(begin,k);

        if (valid(ip))

        {

            ips.push_back(ip);

            find(res,ips,kth+1,begin+k,s);

            ips.pop_back();

        }

    }

    return;

}

vector<string> restoreIpAddresses(string s)

{

    vector<string> res;

    if(s.size()<4||s.size()>12)return res;

    vector<string> ips;

    find(res, ips, 1, 0,s);

    return res;

}

};

 

你可能感兴趣的:(LeetCode)