https://leetcode.com/problems/restore-ip-addresses/discuss/30944/Very-simple-DFS-solution
1 class Solution { 2 List<String> res = new ArrayList<>(); 3 public List<String> restoreIpAddresses(String s) { 4 backtrack(s, "", 0, 0); 5 return res; 6 7 } 8 9 public void backtrack(String s, String str, int index, int count) { 10 if(count > 4) return; 11 if(count == 4 && index == s.length()) res.add(str); 12 13 for(int i = 1; i < 4; i++) { 14 if(index + i > s.length()) break; 15 String sub = s.substring(index, index + i); 16 if((sub.startsWith("0") && sub.length() > 1) || (Integer.parseInt(sub) > 255)) break; 17 backtrack(s, str + sub + (count == 3?"" : "."), index + i, count+1); //因为是直接str+什么什么 所以不改变str本身的值 18 19 } 20 } 21 }