Title: https://leetcode.com/problems/permutations/
The title is to ask for an array of the entire arrangement, tried a lot of non-recursive methods are unsuccessful, feel that this problem has a recursive will be more convenient.
The way to solve this problem is to select a number from the array, and then arrange the rest of the number in the group.
Maintain a result set, which is the number that has been completed, such as the set is {one-time}, the first to select a number to do the whole arrangement, then this result has [[1],[2],[3]]
1 The corresponding non-aligned set is {2,3},2 corresponding to the non-aligned combination is {1,3} ...
After constructing a permutation set, recursively selects a number for the permutation set, adding to the arranged set.
The condition for recursive exit is that the set that is not aligned is empty.
Package Leet;import Java.util.arraylist;import Java.util.collections;import java.util.linkedlist;import Java.util.list;public class permutations {list<list<integer>> result = new ArrayList ();p ublic list<list <Integer>> permute (int[] nums) {
If not aligned with NULL, returns the sequence if (nums.length = = 0) {return result;} list<integer> list = new LinkedList ();
The number to be arranged is constructed into a linked list, which facilitates the subsequent use of list<integer> num = new LinkedList (); int i;for (i=0;i<nums.length;i++) {Num.add (nums[i]) ;}
Go to Heavy collections.sort (num); for (I=0;i<num.size () -1;i++) {if (Num.get (i) = = Num.get (i+1)) {Num.remove (Num.get (i));}}
Start constructing permutenum (num,list); return result;} public void Permutenum (list nums,list list) {int i;
At the end of a construct, add this order to result if (nums.size () = = 0) {result.add (list); return;} For (I=0;i<nums.size (); i++) {
For each number in the unordered collection, construct a new sequence, and join as a number in the Permutation collection for list var = new LinkedList (), Var.addall (list), Var.add (Nums.get (i));//construct unsorted sequence, Remove the number just added from the sequence list tmp= new LinkedList (); Tmp.addall (nums); Tmp.remove (Nums.get (i));//recursively sort new sorted combined and unordered sets Permutenum ( Tmp,var);} return;} public static void Main (String args[]) {int[] nums = {1,2,3,2,3,1,4}; Permutations p = new permutations ();p. Permute (Nums);}}
To find the array in full order