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;
                }
            }
        }
    }
  • 相关阅读:
    小程序行内点击事件冲突解决
    小程序带参返回刷新主页面
    小程序时间选择器(精确到秒)
    Bootstrap-Table事件和方法
    JS 解决txt文件直接打开而不是下载
    Bootstrap-Table进阶篇
    Bootstrap-Table入门篇
    Angular+SSM+Ajax的简单购物车实例
    Angular实现简单购物车
    K3BOS单据获取单据体行数
  • 原文地址:https://www.cnblogs.com/Gryffin/p/6228500.html
Copyright © 2011-2022 走看看