public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); helper(nums, 0, new ArrayList<Integer>(), res); return res; }
privatevoidhelper(int[] nums, int cur, List<Integer> list, List<List<Integer>> res){ if(cur == nums.length) { List<Integer> t = new ArrayList<Integer>(list); res.add(t); return; } for(int i = cur; i < nums.length; ++i) { swap(nums, cur, i); list.add(nums[cur]); helper(nums, cur + 1, list, res); swap(nums, cur, i); list.remove(list.size() - 1); } }
privatevoidswap(int[] nums, int i, int j){ int t = nums[i]; nums[i] = nums[j]; nums[j] = t; }
Permutations with duplicates
Given a collection of numbers that might contain duplicates, return all possible unique permutations.