题目:
解析:
这题设计递归函数,主要把看如何剪枝
代码:
javaclass Solution { private List<List<Integer>> ret; private List<Integer> path; private boolean[] check; public List<List<Integer>> permuteUnique(int[] nums) { ret = new ArrayList<>(); path = new ArrayList<>(); check = new boolean[nums.length]; Arrays.sort(nums);// dfs(nums,0); return ret; } //pos是决策树层数 private void dfs(int[] nums,int pos){ if(pos == nums.length){ ret.add(new ArrayList<>(path)); return; } for(int i = 0; i < nums.length; i++){ //不合法分支剪枝 if(check[i] == true || i != 0 && nums[i] == nums[i-1] && check[i-1] == false) continue; if(check[i] == false){ path.add(nums[i]); check[i] = true; dfs(nums,pos+1); //恢复现场 path.remove(path.size()-1); check[i] = false; } } } }
穷举vs暴搜vs深搜vs回溯vs剪枝专题一>全排列II
robin_suli2024-12-24 15:27
相关推荐
aaaameliaaa1 小时前
字符函数和字符串函数城管不管2 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别月疯2 小时前
二分法算法(水平等分图形面积)豆瓣鸡3 小时前
算法日记 - Day3白白白小纯3 小时前
算法篇—反转链表Achou.Wang3 小时前
深入理解go语言-第5章 并发编程——Go的灵魂The Chosen One9853 小时前
高进度算法模板速记(待完善)土豆.exe6 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法黄河123长江6 小时前
有限Abel群的结构()Jerry7 小时前
LeetCode 92. 反转链表 II
