93. 复原 IP 地址

原题

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

思路

回溯法

复杂度

时间:O(n!)
空间:O(n!)

Python代码

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        ans = []

        def isValidIP(sub):
            if 0 <= int(sub) <= 255:
                # 包含前导0
                if len(sub) > 1 and sub[0] == '0':
                    return False 
                else:
                    return True 
            else:
                return False


        def dfs(start, path):
            # 返回条件
            if start == len(s) and len(path) == 4:
                ans.append('.'.join(path))
                return 
            if start == len(s) and len(path) != 4:
                return 
            for j in range(start, len(s)):
                sub = s[start: j+1]
                if isValidIP(sub):
                    path.append(sub)
                    dfs(j+1, path)
                    # 还原
                    path.pop()

        dfs(0, [])
        return ans 
        

Go代码

func restoreIpAddresses(s string) []string {
	var ans []string
	var isValidIP = func(sub string) bool {
		n, _ := strconv.Atoi(sub)
		if 0 <= n && n <= 255 {
			// 包含前导0
			if len(sub) > 1 && sub[0] == '0' {
				return false
			} else {
				return true
			}
		} else {
			return false
		}
	}
	// 匿名函数
	var dfs func(int, []string)
	dfs = func(start int, path []string) {
		// 返回条件
		if start == len(s) && len(path) == 4 {
			addr := strings.Join(path, ".")
			ans = append(ans, addr)
			return
		}
		if start == len(s) && len(path) != 4 {
			return
		}
		for j := start; j < len(s); j++ {
			sub := s[start : j+1]
			if isValidIP(sub) {
				path = append(path, sub)
				dfs(j+1, path)
				// 还原
				path = path[:len(path)-1]
			}
		}
	}

	dfs(0, []string{})
	return ans
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值