Algorithm: backtracking six full array array Permutations II II

topic

地址:https://leetcode.com/problems/permutations-ii/
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]
]

Backtracking DFS achieve

Ideas:

  1. To the array nums sort;
  2. With Boolean type array used whether each location have been used record.
  3. Focus condition if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]), if not the first position, and a position to keep up the value of the same, and have not used, do not explain the position of the head. For counter-examples [1, 1, 2], without this condition, two results can occur. This condition also [2, 1, 1]to de-emphasis, such as 1 second at position 1, because of the conditions !used[i - 1] == true, the success of de-emphasis.
  4. Normally choose, list.remove(list.size() - 1)the statement said they did not choose, used[i] = falseand the reset state.
package backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

// https://leetcode.com/problems/permutations-ii/
public class PermutationsII {

  public static void main(String[] args) {
    PermutationsII obj = new PermutationsII();
    int[] input = {1,1,2};
    List<List<Integer>> resultList = obj.permuteUnique(input);
    System.out.println(Arrays.toString(resultList.toArray()));
  }

  public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> resultList = new ArrayList<List<Integer>>();
    Arrays.sort(nums);
    boolean[] used = new boolean[nums.length];
    if (nums == null || nums.length == 0) {
      return resultList;
    }
    dfs(nums, resultList, new ArrayList<Integer>(), used);

    return resultList;
  }

  private void dfs(int[] nums, List<List<Integer>> resultList, List<Integer> list, boolean[] used) {
    if (list.size() == nums.length) {
      resultList.add(new ArrayList<Integer>(list));
      return;
    }
    for (int i = 0; i < nums.length; i++) {
      if (used[i]) {
        continue;
      }
      if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
        continue;
      }
      used[i] = true;
      list.add(nums[i]);
      dfs(nums, resultList, list, used);
      used[i] = false;
      list.remove(list.size() - 1);
    }
  }
}

Download

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/PermutationsII.java

Published 127 original articles · won praise 12 · views 20000 +

Guess you like

Origin blog.csdn.net/zgpeace/article/details/103802369