LeetCode 47. Permutations II(排列)
2016-05-21 05:23
525 查看
原题网址:https://leetcode.com/problems/permutations-ii/
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
and
方法一:深度优先搜索,使用集合检查重复。
方法二:运用循环右移、左移的方法,巧妙的避免使用used集合。
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],
and
[2,1,1].
方法一:深度优先搜索,使用集合检查重复。
public class Solution { private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } private void dfs(int[] nums, int from, List<List<Integer>> results) { if (from == nums.length) { List<Integer> result = new ArrayList<Integer>(); for(int i=0; i<nums.length; i++) result.add(nums[i]); results.add(result); return; } Set<Integer> used = new HashSet<Integer>(); for(int i=from; i<nums.length; i++) { if (used.contains(nums[i])) continue; used.add(nums[i]); swap(nums, from, i); dfs(nums, from+1, results); swap(nums, from, i); } } public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> results = new ArrayList<>(); if (nums == null || nums.length == 0) return results; dfs(nums, 0, results); return results; } }
方法二:运用循环右移、左移的方法,巧妙的避免使用used集合。
public class Solution { private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } private void dfs(int[] nums, int from, List<List<Integer>> results) { if (from == nums.length-1) { Integer[] result = new Integer[nums.length]; for(int i=0; i<nums.length; i++) result[i] = nums[i]; results.add(Arrays.asList(result)); return; } // 循环一轮下来,nums[from..nums.length]相当于循环右移了一次。 for(int i=from; i<nums.length; i++) { if (i>from && nums[i]==nums[from]) continue; swap(nums, from, i); dfs(nums, from+1, results); } // 循环左移回去 for(int i=nums.length-1; i>=from; i--) { swap(nums, from, i); } } public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> results = new ArrayList<>(); if (nums == null || nums.length == 0) return results; Arrays.sort(nums); dfs(nums, 0, results); return results; } }
相关文章推荐
- LeetCode 46. Permutations(排列)
- python基础
- python基础
- LeetCode 45. Jump Game II(跳格子)
- 山寨Besiege(四)操控轴
- BigBlueButton简介
- Moodle简介
- Bigbluebutton服务执行过程及相关配置文件
- LeetCode 44. Wildcard Matching(模糊匹配)
- 大数据和Android
- Mvp架构的使用
- 【三分法/数学公式】B君的圆锥【51nod】【BSG白山极客挑战赛】
- Bigbluebutton中文乱码问题
- Bigbluebutton安装过程
- [置顶] Android自定义View(二、深入解析自定义属性)
- Android自定义View(二、深入解析自定义属性)
- 蓝桥杯国赛前一周深夜思索
- 辛星浅析yaml
- 使用GSON解析一个复杂的json
- strtok 和 sscanf 结合输入