46. Permutations 全排列,无重复
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
if(temp.contains(nums[i])) continue;temp里加过了的话,就不加了。这句话得有
class Solution { public List<List<Integer>> permute(int[] nums) { //cc List<List<Integer>> results = new ArrayList<List<Integer>>(); if (nums == null || nums.length == 0) return results; //排序一下 Arrays.sort(nums); dfs(nums, new ArrayList<Integer>(), 0, results); return results; } public void dfs(int[] nums, List<Integer> temp, int start, List<List<Integer>> results) { //exit if (temp.size() == nums.length) results.add(new ArrayList<>(temp)); for (int i = 0; i < nums.length; i++) { // if ((i > start) && (nums[i] == nums[i - 1])) // continue; if(temp.contains(nums[i])) continue; temp.add(nums[i]); dfs(nums, temp, i + 1, results); temp.remove(temp.size() - 1); } } }