Permutations && Permutations ii
来源:互联网 发布:北京java应届生工资 编辑:程序博客网 时间:2024/05/16 07:40
Permutations 中不带有重复元素
Permutations II 中带有重复元素
Permutations
java
public class Solution { /* * @param nums: A list of integers. * @return: A list of permutations. */ public List<List<Integer>> permute(int[] nums) { // write your code here List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length == 0) { result.add(new ArrayList<Integer>()); return result; } List<Integer> path = new ArrayList<>(); Set<Integer> set = new HashSet<>(); dfs(nums, path, result, set); return result; } private void dfs(int[] nums, List<Integer> path, List<List<Integer>> result, Set<Integer> set) { if (path.size() == nums.length) { result.add(new ArrayList<Integer>(path)); return; } for (int i = 0; i < nums.length; i++) { if (!set.contains(nums[i])) { set.add(nums[i]); path.add(nums[i]); dfs(nums, path, result, set); set.remove(nums[i]); path.remove(path.size() - 1); } } }}
Permutations II
java
public class Solution { /* * @param : A list of integers * @return: A list of unique permutations */ public List<List<Integer>> permuteUnique(int[] nums) { // write your code here List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length == 0) { result.add(new ArrayList<Integer>()); return result; } List<Integer> path = new ArrayList<>(); boolean[] visit = new boolean[nums.length]; Arrays.sort(nums); dfs(nums, path, result, visit); return result; } private void dfs(int[] nums, List<Integer> path, List<List<Integer>> result, boolean[] visit) { if (path.size() == nums.length) { result.add(new ArrayList<Integer>(path)); return; } for (int i = 0; i < nums.length; i++) { if ((visit[i] == true) || (i != 0 && nums[i] == nums[i - 1] && visit[i - 1] == false)) { continue; } else { path.add(nums[i]); visit[i] = true; dfs(nums, path, result, visit); visit[i] = false; path.remove(path.size() - 1); } } }}
阅读全文
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Permutations and Permutations II
- Permutations && Permutations ii
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- Permutations II
- 万树IT:学软件测试的几大优势
- BZOJ 4552: [Tjoi2016&Heoi2016]排序 [二分][线段树]
- 局域网中Controller重要蓝图节点
- Maven项目自动部署到tomcat
- 使用CSDN-markdown编辑器
- Permutations && Permutations ii
- TabLayout与ViewHolder的交互
- MFC之在对话框创建菜单、工具栏、状态栏
- URL编码
- 树
- 数据结构实验之排序五:归并求逆序数
- windows安装shapely
- JavaWeb三大组件之Servlet
- ActiveMQ消息中间件学习(一)