LeetCode·93.复原IP地址·递归+回溯+剪枝

链接:https://leetcode.cn/problems/restore-ip-addresses/solution/-by-xun-ge-v-5dia/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

题目

 

示例

 

思路

解题思路
整体思路还是容易想的,但是具体实现细节还是比较多

整体思路,题目需要我们进行字符串的分割,很容易可以想到分割和分组其实是差不多的,只是分组可以打乱进行,而分割是整体进行。
运用分组的思想进行分割,使用递归回溯思想

具体实现
我们枚举每一个子串,判断每一个子串是否满足条件,当某子串满足条件时,分割当前字符串,再将分割点之后的字符串重复上面动作,直到分割到最后时,保存有效字符串组合

需要满足什么样的条件呢?
主要考虑到如下三点:

  • 子串以0为开头的数字不合法
  • 子串里有非正整数字符不合法
  • 子串如果大于255了不合法

对于下标是否要+1,可以代入具体数组算一下,免得去想

代码注释超级详细

代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

bool isValid(char * s, int i, int j)
{
    if(i > j) return false;
    if (s[i] == '0' && i != j) { // 0开头的数字不合法
            return false;
    }
    int num = 0;
    for (i; i <= j; i++) {
        if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法
            return false;
        }
        num = num * 10 + (s[i] - '0');
        if (num > 255) { // 如果大于255了不合法
            return false;
        }
    }
    return true;
}

void dfs(char * s, char ** ans, int * returnSize, char * path, int path_i, int index, int len, int n)
{
    if(n == 3)//.号个数为三,只需要判断剩余子串是否满足要求
    {
        if(isValid(s, index, len-1))//满足条件的有效子串组合
        {
            strncpy(path+path_i, s+index, len -index);
            ans[(*returnSize)] = (char *)malloc(sizeof(char) * (len+4));
            memcpy(ans[(*returnSize)], path, sizeof(char) * (len+4));
            (*returnSize)++;
        }
        return;
    }
    for(int i = index; i < len && i - index < 3; i++)//枚举有可能的分割点,剪枝 i - index < 3,数值最多三位
    {
        if(isValid(s, index, i))//进一步剪枝,如果子串不满足条件,那么之后不管怎么分割,整个组合都是不满足,提前结束
        {
            strncpy(path+path_i, s+index, i - index + 1);
            path[path_i + i - index + 1] = '.';
            dfs(s, ans, returnSize, path, path_i + i - index + 2, i+1, len, n+1);
        }
        else break;
    }
    return;
}

char ** restoreIpAddresses(char * s, int* returnSize){
    char ** ans = (char **)malloc(sizeof(char *) * 3000);
    *returnSize = 0;
    int len = strlen(s);
    char path[len+4];
    path[len+3] = '\0';
    dfs(s, ans, returnSize, path, 0, 0, len, 0);
    return ans;
}

作者:xun-ge-v
链接:https://leetcode.cn/problems/restore-ip-addresses/solution/-by-xun-ge-v-5dia/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值