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

[LintCode] Permutations

时间:2017-09-28 10:07:25      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:integer   for   ret   perm   turn   lin   use   sam   panel   

Given a list of numbers, return all possible permutations.

You can assume that there is no duplicate numbers in the list.

Example

For nums = [1,2,3], the permutations are:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
Challenge 

Do it without recursion.

 

Solution 1. Recursion

Highlighted line 21 decides at each level, which element should be picked first. Take [1,2,3] as an example, we know all permutations must start with 1, 2, or 3.

used flag ensures that we do not pick the same element more than once.

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> results = new ArrayList<>();
 4         if(nums == null || nums.length == 0) {
 5             results.add(new ArrayList<Integer>());
 6             return results;
 7         }
 8         boolean[] used = new boolean[nums.length];
 9         for(int i = 0; i < used.length; i++) {
10             used[i] = false;
11         }
12         permuteDfs(results, new ArrayList<Integer>(), nums, used);
13         return results;
14     }
15     private void permuteDfs(List<List<Integer>> results, List<Integer> list, 
16                             int[] nums, boolean[] used) {
17         if(list.size() == nums.length) {
18             results.add(new ArrayList<Integer>(list));
19             return;
20         }
21         for(int i = 0; i < nums.length; i++) {
22             if(used[i]) {
23                 continue;
24             }
25             list.add(nums[i]);
26             used[i] = true;
27             permuteDfs(results, list, nums, used);
28             list.remove(list.size() - 1);
29             used[i] = false;
30         }
31     }
32 }

 

Related Problems

Print Numbers By Recursion

Permutation Sequence

Permutations II

 

 

[LintCode] Permutations

标签:integer   for   ret   perm   turn   lin   use   sam   panel   

原文地址:http://www.cnblogs.com/lz87/p/7494145.html

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