leetcode46. 全排列

题目

给定一个没有重复数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

解题思路

使用回溯算法进行深度遍历;向list添加任意nums[i],如果nums[i]已经存在,则不放入,直到list的长度等于nums的长度,则res加入list。.

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public List<List<Integer>> permute(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
backstack(res, nums, list, 0);
return res;
}
public void backstack(List<List<Integer>> res, int[]nums, List<Integer> list, int len) {
if(len == nums.length) {
res.add(new ArrayList<>(list));
return ;
}
for(int i = 0; i < nums.length; i ++) {
if(!list.contains(nums[i])) {
list.add(nums[i]);
backstack(res, nums, list, len +1);
list.remove(list.size()-1);
}
}
}
}

提交结果

成功
显示详情
执行用时 : 5 ms, 在Permutations的Java提交中击败了68.78% 的用户
内存消耗 : 38 MB, 在Permutations的Java提交中击败了81.41% 的用户