LeetCode 46: Permutations

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 46: Permutations相关的知识,希望对你有一定的参考价值。

Tips :

1. Need to new array list since it is passed by reference. All the values will be cleaned up the original data is used.

2. For iteraive, no need to copy the last loop result since it should be a new B+ tree layer generation.

Iterative :

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         result.add(new ArrayList<>());
 5         
 6         for (int i = 0; i < nums.length; i++) {
 7             List<List<Integer>> newResult = new ArrayList<>();
 8             for (List<Integer> internal : result) {
 9                 for (int j = 0; j <= i; j++) {
10                     List<Integer> newInternal = new ArrayList<>(internal);
11                     newInternal.add(j, nums[i]);
12                     newResult.add(newInternal);
13                 }
14             }
15             result = newResult;
16         }
17         return result;
18     }
19 
20 }

 

 

Recursive : 

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         DFS(result, new ArrayList<>(), nums, new boolean[nums.length]);
 5         return result;
 6     }
 7     
 8     private void DFS(List<List<Integer>> result, List<Integer> currentList, int[] nums, boolean[] visited) {
 9         if (currentList.size() == nums.length) {
10             result.add(new ArrayList<>(currentList));
11             return;
12         }
13         
14         for (int i = 0; i < nums.length; i++) {
15             if (visited[i]) {
16                 continue;
17             }
18             visited[i] = true;
19             currentList.add(nums[i]);
20             DFS(result, currentList, nums, visited);
21             currentList.remove(currentList.size() - 1);
22             visited[i] = false;
23         }
24     }
25 }

 

以上是关于LeetCode 46: Permutations的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 46-Permutations and 47-Permutations II

[LeetCode] 46. Permutations(全排列)

[leetcode][46] Permutations

LeetCode 46. Permutations

LeetCode 46: Permutations

Leetcode 46 Permutations