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]
]
全排列是所有元素,所以index必须从0开始
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); backtrack(nums, new ArrayList<>(), list); return list; } private void backtrack(int [] nums, List<Integer> tempList, List<List<Integer>> list){ if (tempList.size() == nums.length) list.add(new ArrayList<>(tempList)); for(int i = 0; i < nums.length; i++){ if(tempList.contains(nums[i])) continue; tempList.add(nums[i]); backtrack(nums, tempList, list); tempList.remove(tempList.size() - 1); } } }