码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Permutations II 解题报告

时间:2014-12-03 20:58:01      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   java   

Permutations II

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].

bubuko.com,布布扣

SOLUTION 1:

还是经典的递归模板。需要处理的情况是:我们先把Num排序,然后只能连续地选,这样就可以避免生成重复的solution.
例子:1 2 3 4 4 4 5 6 7 8
444这个的选法只能:4, 44, 444连续这三种选法

我们用一个visit的数组来记录哪些是选过的。

bubuko.com,布布扣
 1 public class Solution {
 2     public List<List<Integer>> permuteUnique(int[] num) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         if (num == null || num.length == 0) {
 5             return ret;
 6         }
 7         
 8         // For deal with the duplicate solution, we should sort it.
 9         Arrays.sort(num);
10         boolean[] visit = new boolean[num.length];
11         
12         dfs(num, new ArrayList<Integer>(), ret, visit);
13         
14         return ret;
15     }
16     
17     public void dfs(int[] num, ArrayList<Integer> path, List<List<Integer>> ret, boolean[] visit) {
18         int len = num.length;
19         if (path.size() == len) {
20             ret.add(new ArrayList<Integer>(path));
21             return;
22         }
23         
24         for (int i = 0; i < len; i++) {
25             // 只能连续地选,这样就可以避免生成重复的solution.
26             // 例子:1 2 3 4 4 4 5 6 7 8
27             // 444这个的选法只能:4, 44, 444连续这三种选法
28             if (visit[i] || (i != 0 && visit[i - 1] && num[i] == num[i - 1])) {
29                 continue;
30             }
31             
32             // 递归以及回溯
33             visit[i] = true;
34             path.add(num[i]);
35             dfs(num, path, ret, visit);
36             path.remove(path.size() - 1);
37             visit[i] = false;
38         }
39     }
40 }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/permutation/PermuteUnique.java

LeetCode: Permutations II 解题报告

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4141085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!