Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]Have the following permutations:
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], And[3,2,1].
Search for the following tree by using the deep search method (for example, an incomplete tree). The path that passes through each search for the leaves is an arrangement.
The Code is as follows:
1 public class Solution { 2 public List<List<Integer>> permute(int[] num) { 3 List<List<Integer>> answerList = new ArrayList<List<Integer>>(); 4 ArrayList<Integer> currentList = new ArrayList<Integer>(); 5 boolean[] visited = new boolean[num.length]; 6 DS(answerList, visited, num, currentList); 7 return answerList; 8 } 9 10 public void DS(List<List<Integer>> answerList,boolean[] visited,int[] num,ArrayList<Integer> currentList){11 boolean find = true;12 for(int i = 0;i < num.length;i++){13 if(!visited[i]){14 currentList.add(num[i]);15 visited[i]= true;16 DS(answerList, visited, num, currentList);17 visited[i]= false;18 currentList.remove(currentList.size()-1);19 find = false;20 }21 }22 if(find){23 ArrayList <Integer> temp = new ArrayList<Integer>(currentList);24 answerList.add(temp);25 }26 }27 }
In the above Code, the DS function is a recursive deep Priority Search function. The answerlist records all the final sorting results, and the visited data records whether the corresponding node is in the accessed path at a certain time point, currentlist is the path that has passed. Note that after finding a new path, you need to apply for a memory space for this path to store it (as shown in line 23rd of code ), otherwise, the arrangement that has been stored in the answerlist when the currentlist is modified will also be modified.