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], [3,2,1] ]
public class Solution {
public List<List<Integer>> permute(int[] nums) {
ArrayList<List<Integer>> ans = new ArrayList<List<Integer>>();
if(nums.length==0||nums==null) return null;
ArrayList<Integer> cur = new ArrayList<Integer>();
boolean[] visited = new boolean[nums.length];
buildAns(nums,cur,ans,visited);
return ans;
}
private static void buildAns(int nums[],ArrayList<Integer> cur, ArrayList<List<Integer>> ans,boolean[] visited){
if(cur.size()==nums.length){
ans.add(new ArrayList<Integer>(cur));
return;
}
for(int i=0;i<nums.length;i++){
if(!visited[i]){
cur.add(nums[i]);
visited[i]=true;
buildAns(nums,cur,ans,visited);
cur.remove(cur.size()-1);
visited[i]=false;
}
}
}
}
每个数字只能出现一次
II:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2]
have the following unique permutations:
[ [1,1,2], [1,2,1], [2,1,1] ]与上题不同的是,这个数组中有重复的数字,所以要去除重复,其他的代码不变
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
ArrayList<List<Integer>> ans = new ArrayList<List<Integer>>();
ArrayList<Integer> cur = new ArrayList<Integer>();
if(nums.length==0||nums==null) return null;
boolean[] visited = new boolean[nums.length];
findAns(nums,cur,ans,visited);
return ans;
}
private static void findAns(int[] nums,ArrayList<Integer> cur, ArrayList<List<Integer>> ans, boolean[] visited){
if(cur.size()==nums.length){
ans.add(new ArrayList<Integer>(cur));
return;
}
for(int i=0;i<nums.length;i++){
if(i>0 && nums[i-1]==nums[i] && !visited[i-1]) continue;// 去除重复的排列
if(!visited[i]){
cur.add(nums[i]);
visited[i]=true;
findAns(nums,cur,ans,visited);
cur.remove(cur.size()-1);
visited[i]=false;
}
}
}
}