• [LeetCode] 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)
    » Solve this problem

    [解题思路]
    递归的将数字串分成四个部分,每个部分满足0<=p<=255。要注意一些边界case,比如010是没有意思的,“0.10.010.1”。

    1:       vector<string> restoreIpAddresses(string s) {   
    2: vector<string> col;
    3: string ip;
    4: partitionIP(s, 0, 0, ip, col);
    5: return col;
    6: }
    7: void partitionIP(string s, int startIndex, int partNum,
    8: string resultIp, vector<string>& col)
    9: {
    10: //max: 3 bits per partition
    11: if(s.size() - startIndex > (4-partNum)*3) return;
    12: //min: 1 bit per partition
    13: if(s.size() - startIndex < (4-partNum)) return;
    14: if(startIndex == s.size() && partNum ==4)
    15: {
    16: resultIp.resize(resultIp.size()-1);
    17: col.push_back(resultIp);
    18: return;
    19: }
    20: int num =0;
    21: for(int i = startIndex; i< startIndex +3; i++)
    22: {
    23: num = num*10 + (s[i]-'0');
    24: if(num<=255)
    25: {
    26: resultIp+=s[i];
    27: partitionIP(s, i+1, partNum+1, resultIp+'.', col);
    28: }
    29: if(num ==0)//0.0.0.0 valid, but need to avoid 0.1.010.01
    30: {
    31: break;
    32: }
    33: }
    34: }



  • 相关阅读:
    gdb调试工具
    一步步理解Linux之中断和异常
    英语感受 5月份英语思维
    2013年6月4日星期二
    2013年5月29日星期三
    2013年6月3日星期一
    第22周六晚上
    2013年5月26日星期日
    2013年5月28日20:16:21
    2013年6月2日星期日
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078966.html
Copyright © 2020-2023  润新知