[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)
题意:
给定一个字符串,将它划分为IP地址的格式。
思路:
这是一道明显的回溯的题目。一个IP地址可以分为四个位置,每个位置的数字的位数理论可能性是1位,2位或者3位。但是需要判断这个数字能否作为该位置上的数。

  1. 首先需要满足如果位数超过一位,那么第一位不能是0。
  2. 如果是三位的数字,那么该数字不能比255大。
  3. 剩余的字符要能够满足接下来的那些位置。比如剩余k个字符,还有m个位置没有填充,那么k<=3*m && k >= m,就是说k最小要能够满足每一位上可以放一个数,k最大不能超过每一位放三个数字。

以上。
代码如下:

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        if(s == "")return vector<string>();
        vector<string> result;
        vector<string> temp;
        backTracking(s,0,result,temp,1);
        return result;
    }
    void backTracking(string s,int start,vector<string>& result,vector<string>& temp,int count){
        if(count == 4){
            if(s.size() - start > 1 && (s.substr(start))[0] == '0')return;
            else if(s.size() - start > 3)return;
            else if(s.size() - start == 3 && (s.substr(start)) >  "255")return;
            string ss = temp[0] + temp[1] + temp[2] + s.substr(start);
            result.push_back(ss);
            cout<<ss<<endl;
            return;
        }
        else if(count == 4)return;
        for(int i = 1; i <= 3; i++){
            if(s.size() - start- i > (4 - count)*3)continue;
            else if(s.size() - start - i < (4-count))break;
            string stemp = s.substr(start,i);
            if(i > 1 && stemp[0] == '0')continue;
            if(i == 3 && stemp > "255")continue;

            temp.push_back(stemp+".");
            backTracking(s,start + i,result,temp,count + 1);
            temp.pop_back();

        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值