标签:
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。
标签:
原文地址:http://www.cnblogs.com/dingjunnan/p/5205904.html