題目地址:https://leetcode.com/problems/permutations-ii/spa
題目解析:和permutations同樣,只須要在交換元素是判斷元素是否重複便可code
題目解答:blog
public class Solution { public List<ArrayList<Integer>> permuteUnique(int[] num) { List<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>(); if(num == null || num.length == 0){ return ret; } Arrays.sort(num); permute(num,0,ret); return ret; } private void permute(int[] num,int start,List<ArrayList<Integer>> res){ if(start == num.length - 1){ ArrayList<Integer> temp = new ArrayList<Integer>(); for(int i=0;i<num.length;i++){ temp.add(num[i]); } res.add(temp); return; } for(int i=start;i<num.length;i++){ if(containsDuplicate(num,start,i)){ int temp = num[start]; num[start] = num[i]; num[i] = temp; permute(num,start+1,res); temp = num[start]; num[start] = num[i]; num[i] = temp; } } } private boolean containsDuplicate(int[] arr, int start, int end) { for (int i = start; i <= end-1; i++) { if (arr[i] == arr[end]) { return false; } } return true; } }