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]
]
实现全排序
方法一:
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
permute(nums,new ArrayList<>(),res);
return res;
}
public void permute(int[] nums, List<Integer> now, List<List<Integer>> res) {
if (now.size() == nums.length && !now.isEmpty()) {
res.add(new ArrayList<>(now));
}
for (int index = 0; index < nums.length; index++) {
if (!now.contains(nums[index])) {
now.add(nums[index]);
permute(nums, now, res);
now.remove(now.size()-1);
}
}
}
方法二:根据字典排序 每次找出下一个值 直到没有。具体实现参考47