[LintCode] Permutations

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 }

 

Solution 2. Iteration

 

 

 

Related Problems

Print Numbers By Recursion

Permutation Sequence

Permutations II

 

 

posted @ 2017-09-28 05:47  Review->Improve  阅读(156)  评论(0编辑  收藏  举报