Question
Given a collection of distinct numbers, return all possible permutations.
给出一个无重复数字的集合,返回所有的组合
Example
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution
回溯解。它和subset问题的区别在于subset的123和213是一样的,即顺序是没用的,所以在回溯过程中我们会分别以数组的每一个元素作为头遍历,比如如下:
for(int i = start;i < nums.length; i++){ backtracking(nums, i + 1, res, temp); }
而这里比如{1,2,3}的输入数组,假如我们当前头为2,如果仍然按照之前的算法,2前面的1将不会再遍历到,也就是我们会丢失213这个组合,如果在python中,我们可以通过切片来排除2并重新搜索,在java里我们必须每次都遍历整个数组,然后用temp.contain(nums[i])来判断该元素是否已添加:
for(int i = 0; i < nums.length; i++){ if(temp.contains(nums[i])) continue; backtracking(nums, res, temp); }
完整代码如下:
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); backtracking(nums, res, new ArrayList<>()); return res; } public void backtracking(int[] nums, List<List<Integer>> res, List<Integer> temp){ if(temp.size() == nums.length){ res.add(new ArrayList<>(temp)); return; } for(int i = 0; i < nums.length; i++){ if(temp.contains(nums[i])) continue; temp.add(nums[i]); backtracking(nums, res, temp); temp.remove(temp.size() - 1); } } }