LeetCode93. Restore IP Addresses(C++)

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

解题思路:回溯剪枝,从题目本身来看,将一串数字字符串分为4份,要保证每一份转换成的数字在0-255之间。其中需要留意,不可以将001(类似格式)作为单独一份,所以当遍历到的数字为0,只能单独为一份。

class Solution {
public:
    vector<string>ans;
    vector<int>tempans;
    vector<string> restoreIpAddresses(string s) {
        dfs(s, 0, 0);
        return ans;
    }
    void dfs(string s, int cur, int cnt){
        if(cur == s.length() && cnt == 4){
            string res = to_string(tempans[0]);
            for(int i = 1; i < tempans.size(); ++ i)
                res += '.' + to_string(tempans[i]);
            ans.push_back(res);
            return;
        }
        if(cur == s.length() || cnt == 4)
            return;
        string temp;
        if(s[cur] == '0'){
            tempans.push_back(0);
            dfs(s, cur+1, cnt+1);
            tempans.pop_back();
        }
        else{
            for(int len = 1; len <= 3; ++ len){
                if(cur + len > s.length())
                    break;
                int num = stoi(s.substr(cur, len));
                if(num > 255)
                    break;
                tempans.push_back(num);
                dfs(s, cur+len, cnt+1);
                tempans.pop_back();
            }
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值