Leetcode -- permutations II

Source: Internet
Author: User

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

Original question link: https://oj.leetcode.com/problems/permutations-ii/

Question: given a set of repeated elements, all possible independent arrays are returned.

Idea: you only need to modify the full sorting of the previous question. First, sort the array. In this way, the same elements are adjacent, if the front and back elements are the same, the same value is skipped.

public List<List<Integer>> permuteUnique(int[] num) {if (num == null)return null;List<List<Integer>> result = new ArrayList<List<Integer>>();if (num.length == 0)return result;Arrays.sort(num);permute(num, new boolean[num.length], new ArrayList<Integer>(), result);return result;}public void permute(int[] num, boolean[] isused,ArrayList<Integer> current, List<List<Integer>> result) {if (current.size() == num.length) {result.add(new ArrayList<Integer>(current));return;}for (int i = 0; i < num.length; i++) {if (!isused[i]) {isused[i] = true;current.add(num[i]);permute(num, isused, current, result);isused[i] = false;current.remove(current.size() - 1);while (i + 1 < num.length && num[i + 1] == num[i])i++;}}}


Leetcode -- permutations II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.