Given a collection of distinct 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].
深度优先的框架:
public class Solution {
//深度优先 的框架
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public static int[] path = new int[100];
public static boolean[] v = new boolean[100];
public static void robot(int idx, int[] nums){
if(idx >= nums.length){
List<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++){
tmp.add(nums[path[i]]);
}
ans.add(tmp);
return;
}
for(int i = 0; i < nums.length; i++){
if(v[i] == false){
path[idx] =i;
v[i] = true;
robot(idx+1, nums);
v[i] = false;
}
}
}
public List<List<Integer>> permute(int[] nums) {
ans.clear();
robot(0,nums);
return ans;
}
}