zoukankan      html  css  js  c++  java
  • [leetcode] 47. 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],
      [2,1,1]
    ]

    和一般的Permutation不一样的是,这种permutation需要排序,使相同的元素能够相邻,选取下一个元素的时候,要查看这个元素的前一个元素是否和它相同,如果相同而且没有使用过,就不用选取这个元素,因为如果选取了这个元素,所得的结果被包含于选取了前一个相同元素的结果中。
    代码如下:
    public class Solution {
        int length;
        public List<List<Integer>> permuteUnique(int[] nums) {
            length = nums.length;
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if (length == 0) {
                return result;
            }
            Arrays.sort(nums);
            boolean[] flags = new boolean[length];
            Arrays.fill(flags, false);
            List<Integer> candidate = new ArrayList<Integer>();
            helper(nums, length, flags, result, candidate);
            return result;
        }
        private void helper(int[] nums, int n, boolean[] flags, List<List<Integer>> result, List<Integer> candidate) {
            if (n == 0) {
                result.add(new ArrayList<Integer>(candidate));
            }
            int ll = candidate.size();
            for (int i = 0; i < length; i++) {
                if (!flags[i]) {
                    //if the number appears more than once and the same number before it has not been used
                    if (i != 0 && nums[i] == nums[i - 1] && !flags[i - 1]) {
                        continue;
                    }
                    flags[i] = true;
                    candidate.add(nums[i]);
                    helper(nums, n - 1, flags, result, candidate);
                    candidate.remove(ll);
                    flags[i] = false;
                }
            }
        }
    }
  • 相关阅读:
    uIP tcp/ip协议分析及其在嵌入式系统中的应用
    围棋学习网站 (updating)
    几种代价函数
    浅谈围棋自学入门 写给想自学围棋的业余爱好者
    在 Ubuntu Natty 中解除系统托盘限制
    MATLAB中的CELL用法
    支持向量机(SVM)
    成功思维的三十个模式
    Microsoft Kinect SDK vs PrimeSense OpenNI
    生命中的选择
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6228500.html
Copyright © 2011-2022 走看看