47. Permutations II
来源:互联网 发布:手游直播下什么软件 编辑:程序博客网 时间:2024/06/05 14:16
一开始使用DFS,加使用集合来去重,结果TLE。
改进,参考别人的代码:
1. 先对nums数组做一个排序;
2. 在dfs的时候,判断一下
if (k > 0 && nums[k] == nums[k-1] && flags[k-1]==false) continue;
原因如下:假设有如下序列[x, x, x, a1, a2, x, x, x], 这里是X代表任意数,a1=a2
这段代码是要保证a1排在a2前面,就能够避免重复
List<List<Integer>> permutations = new ArrayList<List<Integer>>(); public void dfs(int i, int[] nums, boolean[] flags, LinkedList<Integer> permutation){ if (i == nums.length){ permutations.add(new LinkedList<>(permutation)); }else{ for (int k = 0; k < nums.length; k ++){ if (flags[k] == false){ if (k > 0 && nums[k] == nums[k-1] && flags[k-1]==false) continue; flags[k] = true; permutation.addLast(nums[k]); dfs(i+1, nums, flags, permutation); flags[k] = false; permutation.removeLast(); } } } } public List<List<Integer>> permuteUnique(int[] nums) { Arrays.sort(nums); boolean[] flags = new boolean[nums.length]; LinkedList<Integer> permutation = new LinkedList<Integer>(); dfs(0, nums, flags, permutation); return this.permutations; }
0 0
- 46. Permutations && 47. Permutations II
- 46. Permutations, 47. Permutations II
- [LeetCode]47.Permutations II
- LeetCode 47.Permutations II
- LeetCode --- 47. Permutations II
- [Leetcode] 47. Permutations II
- [leetcode] 47.Permutations II
- 47.Permutations II
- 47. Permutations II
- LeetCode 47. Permutations II
- 47. Permutations II
- 47. Permutations II LeetCode
- 47. Permutations II
- 47. Permutations II
- 47. Permutations II
- 47. Permutations II
- Leetcode 47. Permutations II
- 47. Permutations II
- 2016.12.17 2016年第四届湘潭大学新生趣味程序设计竞赛 B:Balance
- stm32串口下载出现端口搜索不到或者一直处于连接状态的问题解决办法
- Arrow--轻量级的Android DI 库
- JavaScript判断输入的数是不是素数
- 自学-Shiro的MD5加密及更加严格的盐值加密-08
- 47. Permutations II
- 通过串口在主机和开发板之间传送文件
- zjoi 2008 杀蚂蚁
- Linux配置java环境变量出错直接导致命令无效
- Android上实现一个简单的天气预报APP(三) 获取网络数据
- Python装饰器探究——多个装饰器执行顺序
- eclipse中的Jni开发流程(二)——JNI简便的开发流程
- Linux常用命令-权限管理命令
- 第五章-存储器管理