LeetCode: Restore IP Addresses [093]

来源:互联网 发布:网络租用合同范本 编辑:程序博客网 时间:2024/06/07 00:23

【题目】

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串


【思路】

    IP分为4段,每一段的值域为0-255,也就是说每一位可能是1位,2位或者3位数字
    因此对于一个给定的数字串,我们需要确定4个位置上的值,每个位置有三种可能的位数取值,因此总共要考虑3^4=81中可能IP段划分方案。
    我们可以用递归来求解。


【代码】

class Solution {public:    bool isValid(string num){        if(num.length()==1 && num>="0" && num<="9")return true;        if(num.length()==2 && num>="10" && num<="99")return true;        if(num.length()==3 && num>="100" && num<="255")return true;        return false;    }    void restoreIP(vector<string>&result, vector<string>&ips, int kth, int start, string s){        if(start==s.length()){            if(kth==5){                //返回字符串                string ip=ips[0];                for(int i=1; i<4; i++)                    ip+="."+ips[i];                result.push_back(ip);            }            return;        }                //从s的start位置开始确定ip串中的第kth个数        for(int k=1; k<=3 && start+(k-1)<s.length(); k++){            //向前探k位数字            string num=s.substr(start, k);            if(isValid(num)){                ips.push_back(num);                restoreIP(result, ips, kth+1, start+k, s);                ips.pop_back();            }        }    }    vector<string> restoreIpAddresses(string s) {        vector<string> result;        if(s.length()<4 || s.length()>12)return result; //注意字符串有效长度                vector<string>ips;        restoreIP(result, ips, 1, 0, s);        return result;    }};


0 0
原创粉丝点击