LintCode : Permutations II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode : Permutations II相关的知识,希望对你有一定的参考价值。
import java.util.Collections; class Solution { /** * @param nums: A list of integers. * @return: A list of unique permutations. */ public ArrayList<ArrayList<Integer>> permuteUnique(ArrayList<Integer> nums){ // write your code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (nums == null || nums.size() == 0) { return result; } Collections.sort(nums); boolean[] visited = new boolean[nums.size()]; ArrayList<Integer> list = new ArrayList<Integer>(); permutationHelper(result, list, nums, visited); return result; } private void permutationHelper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, ArrayList<Integer> nums, boolean[] visited) { if (list.size() == nums.size()) { result.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < nums.size(); i++) { if (visited[i] == true || (i != 0 && nums.get(i) == nums.get(i - 1) && visited[i - 1] == false)) { continue; } visited[i] = true; list.add(nums.get(i)); permutationHelper(result, list, nums, visited); list.remove(list.size() - 1); visited[i] = false; } } }
用visited数组来记录哪些是访问过的,visited[i - 1] == false很tricky,可能存在1222......这种情况,用第二个2递归的时候,前面那个2应该是还没有访问的,所以这个时候visited[i - 1] == false。
以上是关于LintCode : Permutations II的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Permutations II
[Lintcode]16. Permutations II/[Leetcode]47. Permutations II
Lintcode16 Permutations II solution 题解