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 }

 

posted on 2017-07-23 07:22  keepshuatishuati  阅读(129)  评论(0编辑  收藏  举报