码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 46: Permutations

时间:2017-07-23 10:17:53      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:int   etc   void   res   sed   nal   tin   layer   als   

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

标签:int   etc   void   res   sed   nal   tin   layer   als   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!