permutations
Given A list of numbers, return all possible permutations.
Example
For nums = [1,2,3] , the permutations is:
[ [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:
Recursive
Permutations problem, with subsets basically is similar, just in to the result in the list, not to join the subset but join the whole arrangement, so to add some conditions, List size equals nums size can join.
classSolution {/** * @paramnums:a List of integers. * @return: A List of permutations. */ PublicArraylist<arraylist<integer>> Permute (arraylist<integer>nums) {ArrayList<ArrayList<Integer>> result =NewArraylist<arraylist<integer>>(); if(Nums = =NULL|| Nums.size () = = 0){ returnresult; } ArrayList<Integer> list =NewArraylist<integer>(); Helper (result, list, nums); returnresult; } Private voidHelper (arraylist<arraylist<integer>> result, arraylist<integer> list, arraylist<integer>nums) { if(list.size () = =nums.size ()) {Result.add (NewArraylist<integer>(list)); return; } for(inti = 0; I < nums.size (); i++){ if(List.contains (Nums.get (i))) {Continue; } list.add (Nums.get (i)); Helper (result, list, nums); List.remove (List.size ()+ W); } }}View Code
Solution 2:
Non-recursive
Non-recursive, using the nine chapters of the answer, the basic idea of using a stack to simulate the DFS process. Recite it, just.
classSolution {/** * @paramnums:a List of integers. * @return: A List of permutations. */ PublicArraylist<arraylist<integer>> Permute (arraylist<integer>nums) {ArrayList<ArrayList<Integer>>permutations=NewArraylist<arraylist<integer>>(); if(Nums = =NULL|| Nums.size () = = 0) { returnpermutations; } intn =nums.size (); ArrayList<Integer> stack =NewArraylist<integer>(); Stack.add (-1); while(Stack.size ()! = 0) {Integer last= Stack.get (Stack.size ()-1); Stack.remove (Stack.size ()-1); //increase The last number intNext =-1; for(inti = last + 1; I < n; i++) { if(!stack.contains (i)) {Next=i; Break; } } if(Next = =-1) { Continue; } //generate the next permutationStack.add (next); for(inti = 0; I < n; i++) { if(!stack.contains (i)) {Stack.add (i); } } //Copy to permutations setarraylist<integer> permutation =NewArraylist<integer>(); for(inti = 0; I < n; i++) {Permutation.add (Nums.get (Stack.get (i))); } permutations.add (permutation); } returnpermutations; }}
[Lintcode] Permutations