码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode No93. Restore IP Addresses

时间:2016-08-11 22:46:44      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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地址是否合法,每一段都要小于等于255,一共四段

Algorithm:

DFS,要注意当前元素为0时,0为一段,继续DFS,00是非法的。

Accepted Code:

class Solution {
public:
    vector<string> res;
    vector<string> restoreIpAddresses(string s) {
        DFS(res,s,"",0,0);
        return res;
    }
    void DFS(vector<string>& res,string s,string t,int count,int k)   //count表示段数,k表示s遍历的位置
    {
        if(count==4&&k==s.size())
        {
            res.push_back(t);
            return;
        }
        else if(count>3)
            return;
        string tmp1=t;
        if(s[k]=='0')        //当前元素为0时,即为一段
        {
            tmp1.push_back(s[k]);
            if(count!=3)
                tmp1.push_back('.');
            DFS(res,s,tmp1,count+1,k+1);
        }
        else
        {
            int sum=0;
            for(int i=k;i<s.size();i++)
            {
                sum=sum*10+(s[i]-'0');
                if(sum<=255)
                {
                    string tmp2=tmp1;              //tmp1为未打点,tmp2已打点成为一段
                    tmp2.push_back(s[i]);
                    tmp1.push_back(s[i]);
                    if(count!=3)                  //第四段即count==3时,尾部不打点
                        tmp2.push_back('.');
                    DFS(res,s,tmp2,count+1,i+1);
                }
                else 
                    break;
            }
        }
    }
};


leetcode No93. Restore IP Addresses

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52186700

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!