permutations(全排列)

时间:2022-09-30 12:51:45

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]
]

这题是列举所有情况,回溯。

每次都是从头开始遍历,往集合中添加元素,但是添加过的元素就不能再添加进去了,所以每次遍历就要判断当前元素有没有被使用过。因为这里没有重复元素,用contains就可以解决。有重复元素,就要有数组。

每次遍历数组,往list中添加元素,但是不能出现重复元素,这里用其他方法跳过比较困难,可以用list的contains方法。

class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums.length<=0) return result;
backtracking(result,new ArrayList<Integer>(),nums);
return result;
} public void backtracking(List<List<Integer>> result, List<Integer> list,int[] nums){
if(list.size()==nums.length){
result.add(new ArrayList<Integer>(list));
return ;
} for(int i=0;i<nums.length;i++){
if(list.contains(nums[i])) continue;//每次都是遍历数组中的每个元素,然后添加不一样的元素(保证不重复)
list.add(nums[i]); backtracking(result,list,nums);
list.remove(list.size()-1); }
}
}