46. Permutations 全排列,無重複
阿新 • • 發佈:2020-08-10
Given a collection ofdistinctintegers, 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(intView Code[] 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); } } }