首页 > 其他 > 详细

LeetCode 46: Permutations

时间:2017-07-23 09:32:58      阅读:259      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/shuashuashua/p/7223514.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!