LeetCode 93. Restore IP Addresses(深搜剪枝)

题目来源:https://leetcode.com/problems/restore-ip-addresses/

问题描述

93. Restore IP Addresses

Medium

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"]

------------------------------------------------------------

题意

给出一个由纯数字组成的字符串,分割该字符串使之成为合法的ip地址,求所有可能的ip地址

------------------------------------------------------------

思路

深搜剪枝。搜索的时候要注意遇到‘0’开头的字符串只能是‘0’,不能是‘01’或者‘012’之类的。剪枝的话我就简单加了位数的剪枝,比如当前还有两段ip但是只剩下1个数字或者剩下超过2*3=6个数字了,就剪枝。

------------------------------------------------------------

代码

class Solution {
    List<String> ret = new LinkedList<String>();
    public List<String> restoreIpAddresses(String s) {
        dfs(s, "", 0, 0);
        return this.ret;
    }
    
    public void dfs(String s, String ip, int ind, int cnt)
    {
        int len = s.length();
        if (cnt == 4)
        {
            if (ind == len) {
                this.ret.add(ip);
            }
            return;
        }
        if (len-ind < 4-cnt || len-ind > 3*(4-cnt)) // 剪枝
        {
            return;
        }
        if (s.charAt(ind) == '0')   // 以0开头的两位以上数字是不合法的
        {
            if (cnt < 3) {
                dfs(s, ip + "0.", ind+1, cnt+1);
            } else {
                dfs(s, ip + "0", ind+1, 4);
            }
            return;
        }
        String tmp;
        for (int i=1; i<=3 && ind+i<=len; i++)
        {
            tmp = s.substring(ind, ind+i);
            Integer num = Integer.parseInt(tmp);
            if (num < 256) {
                if (cnt < 3) {
                    dfs(s, ip + tmp + ".", ind+i, cnt+1);
                } else {
                    dfs(s, ip + tmp, ind+i, 4);
                }
            }
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值