### 题目描述

Tag : 「回溯」、「DFS」

`输入：s = "25525511135"输出：["255.255.11.135","255.255.111.35"]复制代码`

`输入：s = "0000"输出：["0.0.0.0"]复制代码`

`输入：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 <= 201<=s.length<=20
• `​s​`​ 仅由数字组成

### 回溯算法

Java 代码：

`class Solution {    List<String> ans = new ArrayList<>();    char[] cs;    public List<String> restoreIpAddresses(String s) {        cs = s.toCharArray();        dfs(0, cs.length, new ArrayList<>());        return ans;    }    void dfs(int idx, int n, List<Integer> cur) {        if (cur.size() > 4) return ;        if (idx == n) {            if (cur.size() == 4) {                StringBuilder sb = new StringBuilder();                for (int i = 0; i < 4; i++) sb.append(cur.get(i)).append(".");                ans.add(sb.substring(0, sb.length() - 1));            }        } else {            for (int i = idx; i < n; i++) {                int t = 0;                for (int j = idx; j <= i; j++) t = t * 10 + (cs[j] - '0');                if (cs[idx] == '0' && i != idx) break;                if (t > 255) break;                cur.add(t);                dfs(i + 1, n, cur);                cur.remove(cur.size() - 1);            }        }    }}复制代码`

Python 代码：

`class Solution:    def restoreIpAddresses(self, s: str) -> List[str]:        ans = []        def dfs(idx, n, cur):            if len(cur) > 4:                return             if idx == n:                if len(cur) == 4:                    ans.append('.'.join(cur))            else:                for i in range(idx, n):                    t = 0                    for j in range(idx, i + 1):                        t = t * 10 + (ord(s[j]) - ord('0'))                    if s[idx] == '0' and i != idx:                        break                    if t > 255:                        break                    cur.append(str(t))                    dfs(i + 1, n, cur)                    cur.pop()        dfs(0, len(s), [])        return ans复制代码`

TypeScript 代码：

`function restoreIpAddresses(s: string): string[] {    const ans = new Array<string>()    function dfs(idx: number, n: number, cur: Array<number>): void {        if (cur.length > 4) return         if (idx == n) {            if (cur.length == 4) {                let str = ''                for (let i = 0; i < 4; i++) str += cur[i] + "."                ans.push(str.substring(0, str.length - 1))            }        } else {            for (let i = idx; i < n; i++) {                let t = 0                for (let j = idx; j <= i; j++) t = t * 10 + (s.charCodeAt(j) - '0'.charCodeAt(0))                if (s[idx] == '0' && i != idx) break                if (t > 255) break                cur.push(t)                dfs(i + 1, n, cur)                cur.pop()            }        }    }    dfs(0, s.length, new Array<number>())    return ans}复制代码`
• 时间复杂度：爆搜不讨论时空复杂度
• 空间复杂度：爆搜不讨论时空复杂度