47.Permutations-II

47. Permutations II

题目地址

https://leetcode.com/problems/permutations-ii/

https://www.lintcode.com/problem/permutations-ii/description

题目描述

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

代码

public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> results = new ArrayList<>();
    if (nums == null) return results;

    Arrays.sort(nums);

    boolean[] visited = new boolean[nums.length];
    List<Integer> permutation = new ArrayList<Integer>();
    dfs(nums, visited, permutation, results);

    return results;
  }

  private void dfs(int[] nums, boolean[] visited, List<Integer> permutation, List<List<Integer>> results) {
    if (nums.length == permutation.size()) {
      results.add(new ArrayList<Integer>(permutation));
      return;
    }

    for (int i = 0; i < nums.length; i++) {
      if (visited[i]) continue;

      // skipping causes duplicate situations
      if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1] == false) {
        // 假设输入的数组为[1,1,2]。则当第一个1被添加进结果集时,可以继续使用第二个1作为元素添加进结果集从而生成112。同理,当试图将第二个1作为第一个元素添加进结果集时,只要第一个1还没有被使用过,则不可以使用第二个1。因此,112不会被重复的添加进结果集。
        continue;
      }

      permutation.add(nums[i]);
      visited[i] = true;
      dfs(nums, visited, permutation, results);
      visited[i] = false;
      permuation.remove(permutation.size() - 1);
    }

  }
}

Approach 2: 字典序

class Solution {
  public ArrayList<ArrayList<Integer>> permuteUnique(ArrayList<Integer> nums) {
      ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
      if (nums == null || nums.size() == 0) return result;

      // deep copy
      List<Integer> perm = new ArrayList<Integer>(nums);
      Collections.sort(perm);

      while (true) {
        result.add(new ArrayList<Integer>(perm));
        // step1: search the first num[k] < nums[k+1] backward
        int k = -1;
        for (int i = perm.size() - 2; i >= 0; i--) 【
          if (perm.get(i) < perm.get(i + 1)) {
            k = i;
            break;
          }
      }
      // if current rank is the largest, exit while loop
      if (k == -1) break;

      // step2: search teh first perm[k] < perm[l] backward
      int l = perm.size() - 1;
      while (l > k && perm.get(l) <= perm.get(k)) l--;

      // step3: swap perm[k] with perm[l]
      Collections.swap(perm, k, l);

      // step4: reverse between k+1 and perm.length - 1
      reverse(perm, k+1, perm.size() - 1);
    }

        return result;
    }

    private void reverse(List<Integer> nums, int left, int right) {
      for (int l = left, r = right; l < r; l++, r--) {
        Collections.swap(nums, l, r);
      }
  }
}

Last updated