Given a collection of distinct numbers, return all possible permutations.
For 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] ]排列组合,由于数组内部数字数唯一,所以出来的排列组合数不会有重复。采用回溯的方法,获得所有的排列组合情况。程序如下:
class Solution {
public void swap(int[] nums, int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public void traceBacking(int[] nums, List<List<Integer>> llst, int start){
if (start == nums.length){
List<Integer> lst = new ArrayList<>();
for (int val : nums){
lst.add(val);
}
llst.add(lst);
return;
}
for (int i = start; i < nums.length; ++ i){
swap(nums, start, i);
traceBacking(nums, llst, start + 1);
swap(nums, start, i);
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
traceBacking(nums, result, 0);
return result;
}
}