46. 全排列

描述

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

链接

46. 全排列 - 力扣(LeetCode) (leetcode-cn.com)

解法一

 1 class Solution {
 2 
 3     List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
 4     LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
 5     boolean[] used;
 6     public List<List<Integer>> permute(int[] nums) {
 7         if (nums.length == 0){
 8             return result;
 9         }
10         used = new boolean[nums.length];
11         permuteHelper(nums);
12         return result;
13     }
14 
15     private void permuteHelper(int[] nums){
16         if (path.size() == nums.length){
17             result.add(new ArrayList<>(path));
18             return;
19         }
20         for (int i = 0; i < nums.length; i++){
21             if (used[i]){
22                 continue;
23             }
24             used[i] = true;
25             path.add(nums[i]);
26             permuteHelper(nums);
27             path.removeLast();
28             used[i] = false;
29         }
30     }
31 }

 

解法二

 1 // 解法2:通过判断path中是否存在数字,排除已经选择的数字
 2 class Solution {
 3     List<List<Integer>> result = new ArrayList<>();
 4     LinkedList<Integer> path = new LinkedList<>();
 5     public List<List<Integer>> permute(int[] nums) {
 6         if (nums.length == 0) return result;
 7         backtrack(nums, path);
 8         return result;
 9     }
10     public void backtrack(int[] nums, LinkedList<Integer> path) {
11         if (path.size() == nums.length) {
12             result.add(new ArrayList<>(path));
13         }
14         for (int i =0; i < nums.length; i++) {
15             // 如果path中已有,则跳过
16             if (path.contains(nums[i])) {
17                 continue;
18             } 
19             path.add(nums[i]);
20             backtrack(nums, path);
21             path.removeLast();
22         }
23     }
24 }

 

参考

carl

posted @ 2021-12-20 22:46  DidUStudy  阅读(22)  评论(0编辑  收藏  举报