【Leetcode】47. Permutations II 【DFS】
来源:互联网 发布:sqlite数据库访问接口 编辑:程序博客网 时间:2024/05/20 06:25
47. Permutations II
- Total Accepted: 81758
- Total Submissions: 279739
- Difficulty: Medium
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:
[ [1,1,2], [1,2,1], [2,1,1]]
思路:
1、DFS。
2、先排序,再跳过未访问的重复元素。
注意:
1、仅对未访问过的元素进行跳过,用while。
2、每次传入的visited是当前访问过的元素,即上层节点的访问情况。
代码如下:
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> ans = new ArrayList<Integer>(); boolean visited[] = new boolean[nums.length]; Arrays.sort(nums); if(nums.length == 0 || nums == null) return ret; for(int i = 0 ; i < nums.length ; i++){ visited[i] = false; } DFS(ret,nums,visited,ans); return ret; } private void DFS(List<List<Integer>> ret , int[] nums , boolean[] visited , List<Integer> ans){ int len = nums.length; if( ans.size() == len ){ List<Integer> tmp = new ArrayList<Integer>(ans); ret.add(tmp); } for(int i = 0 ; i < len ; i++){ while(i > 0 && i < len && nums[i] == nums[i-1] && visited[i-1] != true) i++; if(i==len) return; if(visited[i]) continue; visited[i] = true; ans.add(nums[i]); DFS(ret,nums,visited,ans); visited[i] = false; ans.remove(ans.size()-1); } } }
0 0
- 【Leetcode】47. Permutations II 【DFS】
- leetcode---permutations-ii---dfs
- [LeetCode]47. Permutations II && DFS及剪枝
- LeetCode 47. Permutations II(生成不同的组合-dfs)
- [LeetCode]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 LeetCode
- Leetcode 47. Permutations II
- LeetCode 47. Permutations II
- LeetCode - 47. Permutations II
- [LeetCode] 47. Permutations II
- leetcode 47. Permutations II
- [LeetCode]--47. Permutations II
- [LeetCode]--47. Permutations II
- 51Nod-1640-天气晴朗的魔法
- 浅谈图片服务器的架构演进
- ionic中获取ng-model绑定的值undefined?
- 风控大数据
- EASY UI tree如何根据部分值来选中checkbox
- 【Leetcode】47. Permutations II 【DFS】
- java学习之路 之 枚举类&注解-注解(Annotation)及练习题
- STM32 uart
- Android开发之实现最简单最酷炫的3D图片浏览效果(二)
- uva10048-Audiophobia-Floyd
- C++中静态成员变量与静态成员函数
- HDU 5569 matrix
- 今天写个关于应用程序界面隐藏标题栏,问题虽然很小,但很重要。
- 在 Cent OS 上使用YUM安装 MySQL 5.7 的正确姿势