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]
]
在其基础上扩展,所以是i + 1。要有个start index的参数
//跳过重复值,同一temp集合中不能出现两次
if(temp.contains(nums[i])) continue;
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 退出的条件,加在dfs里最外一层 if (temp.size() == nums.length) { results.add(new ArrayList<>(temp)); } for (int i = 0; i < nums.length; i++) { if (temp.contains(nums[i])) continue; temp.add(nums[i]); dfs(nums, temp, i + 1, results); temp.remove(temp.size() - 1); } } }