代码随想录训练营第二十八天 | 回溯算法
今天是第二十八天,前面几天的回溯算法不太熟,今天继续巩固
class Solution { List<String> ret = new ArrayList<>(); public List<String> restoreIpAddresses(String s) { LinkedList<String> path = new LinkedList<>(); backTrace(0,s,path); return ret; } public void backTrace(int startIndex, String s, LinkedList<String> path){ if(path.size() > 4) return; // 长度>4剪枝 if(startIndex == s.length() && path.size() == 4){ ret.add(toResult(path)); return; } for(int i = startIndex;i<s.length();i++){ String str = s.substring(startIndex,i+1); if(!isValid(str)) continue; path.offerLast(str); backTrace(i+1,s,path); path.removeLast(); } } public String toResult(LinkedList<String> path){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < path.size(); i++){ sb.append(path.get(i)); if(i != path.size() - 1) sb.append("."); } return sb.toString(); } public boolean isValid(String s){ if(s.length()==1) return true; if(s.length()>3) return false; if(s.charAt(0) == '0') return false; if(Integer.valueOf(s) > 255) return false; return true; } }
标准的回溯模版题
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); res.add(new ArrayList<>()); for(int num : nums){ int n = res.size(); for(int i = 0; i<n; i++){ List<Integer> temp = new ArrayList<>(res.get(i)); temp.add(num); res.add(temp); } } return res; } }
可以有不用回溯的思路
class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> retList = new ArrayList<>(); retList.add(new ArrayList<>()); if(nums == null || nums.length == 0) return retList; Arrays.sort(nums); List<Integer> tmp = new ArrayList<>(); tmp.add(nums[0]); retList.add(tmp); if(nums.length == 1) return retList; int lastLen = 1; for(int i = 1; i < nums.length; i++){ int size = retList.size(); if(nums[i] != nums[i-1]){ lastLen = size; } for(int j = size - lastLen; j < size; j++){ List<Integer> inner = new ArrayList(retList.get(j)); inner.add(nums[i]); retList.add(inner); } } return retList; } }
多了一步去重
今天的题三道题两道没有用回溯,过几天复习到的时候重新用回溯做一遍
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?