Skip to content
本页目录

0093-复原IP地址

https://leetcode.cn/problems/restore-ip-addresses

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。 给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]

示例 2:

输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

提示:

  • 1 <= s.length <= 20
  • s 仅由数字组成

思路 【参考了 131 题,直接做出来了】

回溯:第一层 for 循环依次截取字符串,然后判断加入字符串的数字是否合法,是则 dfs 递归进行下一步判断,否则返回 for循环截取最多3位,因为大于3位的肯定大于 255 ,无需再判断

参考代码

csharp
public class Solution {
	List<string> result = new List<string>();

	private bool IsValid(string digit){
		//前导0判断
		if(digit.Length >1 && digit[0] == '0'){
			return false;
		}
		return Convert.ToInt32(digit) <= 255;
	}

	private void dfs(string s, int begin, List<string> list){
		if(list.Count > 4){
			return;
		}
		if(begin == s.Length && list.Count == 4){
			//输出结果
			string str = "";
			for(int i=0; i<list.Count; i++){
				str += i==0 ? list[i] : "." + list[i];
			}
			result.Add(str);
			return;
		}
		int end = Math.Min(begin+3,s.Length);
		for(int i=begin; i<end; i++){
			string digit = s.Substring(begin,i-begin+1);
			if(IsValid(digit)){
				list.Add(digit);
				dfs(s,i+1,list);
				list.RemoveAt(list.Count - 1);
			}
		}

	}

    public IList<string> RestoreIpAddresses(string s) {
    	List<string> list = new List<string>();
    	dfs(s,0,list);
        return result;
    }
}

复习:20220619

csharp
public class Solution {

    private List<string> result = new List<string>();

    private bool isValid(string num){
        if(num[0] == '0' && num.Length > 1){
            return false;
        }
        int n = Convert.ToInt32(num);
        if(n >=0 && n<=255){
            return true;
        }
        return false;
    }

    private void dfs(string s, int begin, List<string> list){
        if(list.Count > 5){
            return;
        }
        if(begin == s.Length && list.Count == 4){ //输出
            string str = string.Format("{0}.{1}.{2}.{3}",list[0],list[1],list[2],list[3]);
            result.Add(str);
            return;
        }
        int end = begin + 3 > s.Length ? s.Length : begin+3;
        for(int i = begin; i < end; i++){
            string num = s.Substring(begin, i-begin+1);
            if(isValid(num)){
                list.Add(num);
                dfs(s,i+1,list);
                list.RemoveAt(list.Count-1);
            }
        }
    }

    public IList<string> RestoreIpAddresses(string s) {
        List<string> list = new List<string>();
        dfs(s,0,list);
        return result;
    }
}

Released under the MIT License.