代码改变世界

leetcode 93 复原IP地址

2018-08-07 20:15  legend聪  阅读(303)  评论(0编辑  收藏  举报

IP地址,分成四段,每段是0-255,按照每段的长度分别为1,2,3下一段长度分别1,2,3再下一段。。。。。。进行递归遍历,能满足条件的假如res中。比较难想到的就是假如有一段是三位的010是不符合要求的。这点一开始没想到,改成首尾不是0的才执行结果又漏掉了单个0的IP地址,比如0.0.0.0.。除了这两点之外剩下的代码还算好想。

#include<bits/stdc++.h>
using namespace std;
class Solution {
private:
    void getIP(string s,int x,int y,vector<string>&res,string &ans,int sum)//[x,x+y-1]前闭后闭从string s的第x位开始获取y位数字组成IP地址。
    {
        int n;
        n = s.size();
        int i;
        if (x + y -1> n - 1||sum>4)
            return;
        if ((4 - sum) * 3+ x + y-1 < n - 1)//如果剩下的几次都取3个数字都取不完所有元素,那么返回。
            return;
        if (y == 3)
        {
            if (100 * (s[x] - '0') + 10 * (s[x + 1] - '0') + (s[x + 2] - '0') > 255)
                return;
        }
        if (s[x] - '0' == 0&&y!=1)
            return;
        for (i = x; i <= x + y-1; i++)
        {    
            ans.push_back(s[i]);
            if (i == x + y-1&&sum!=4)
                ans.push_back('.');
        }
        if (x + y-1 == n - 1&&sum==4)//第三次取完了所有string s里面的元素,保存结果.
        {
            res.push_back(ans);
            for (i = 0; i < y; i++)//回溯
            {
                ans.pop_back();
            }
            return;
        }
    //    if(y+2<=n-1)
        getIP(s,x+y , 1,res,ans,sum+1);
    //    if(y+3<=n-1)
        getIP(s, x+y , 2,res,ans,sum+1);
    //    if(y+4<=n-1)
        getIP(s, x+y, 3,res,ans,sum+1);
        ans.pop_back();
        for (i = 0; i < y; i++)
            ans.pop_back();
        return;
    }
public:
    vector<string> restoreIpAddresses(string s) {
        int n = s.size();
        vector<string>res;
        string ans;
        ans.clear();
        getIP(s, 0, 1, res, ans, 1);
            ans.clear();
        getIP(s, 0, 2, res, ans, 1);
            ans.clear();
        getIP(s, 0, 3, res, ans, 1);
        return res;
    }
};