[LintCode] Permutations
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] Permutations相关的知识,希望对你有一定的参考价值。
Given a list of numbers, return all possible permutations.
You can assume that there is no duplicate numbers in the list.
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]
]
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的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Permutations II
[Lintcode]16. Permutations II/[Leetcode]47. Permutations II
Lintcode16 Permutations II solution 题解