Given a collection of distinct integers, return all possible permutations.
- Example:
Input: [1,2,3]
Output: [ [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1] ]
解法一——深度优先搜索
需要一个数组来判断当前数字是否已经被用过,如果未被用过,则可以加入list中,当list的长度等于数组长度了则证明list中已经有一次排列了,则将其加入res中,要注意是深拷贝,不能浅拷贝。
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
List<Integer> list=new ArrayList<Integer>();
boolean[] visited=new boolean[nums.length];
permutedfs(nums,visited,list,res);
return res;
}
private void permutedfs(int[] nums, boolean[] visited, List<Integer> list, List<List<Integer>> res) {
// TODO Auto-generated method stub
if(list.size()==nums.length)
{
res.add(new ArrayList<Integer>(list));
return;
}
for(int j=0;j<nums.length;j++)
{
if(visited[j])
continue;
visited[j]=true;
list.add(nums[j]);
permutedfs(nums, visited, list, res);
list.remove(list.size()-1);
visited[j]=false;
}
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Permutations.
Memory Usage: 38.5 MB, less than 51.19% of Java online submissions for Permutations.
解法二——递归
当数组为{1}时,它的全排列为{{1}}
当数组为{1,2}时,它的全排列为{{1,2},{2,1}}
当数组为{1,2,3}时,它的全排列为{{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}}
可以看出其实就是把第n个数插入到{1,2…,n-1}的全排列当中。
public List<List<Integer>> permute(int[] nums) {
if(nums.length==1)
{
List<Integer>l=new ArrayList<Integer>();
l.add(nums[0]);
List<List<Integer>> res=new ArrayList<List<Integer>>();
res.add(l);
return res;
}
List<List<Integer>> res=new ArrayList<List<Integer>>();
int first=nums[0];
int[] newnums=new int[nums.length-1];
for(int i=nums.length-1;i>0;i--)
newnums[i-1]=nums[i];
List<List<Integer>> cur=new ArrayList<List<Integer>>(permute(newnums));
for(List<Integer> l:cur)
{
for(int i=0;i<=l.size();i++)
{
l.add(i, first);
res.add(new ArrayList<Integer>(l));
l.remove(i);
}
}
return res;
}
Runtime: 1 ms, faster than 100.00% of Java online submissions for Permutations.
Memory Usage: 38.5 MB, less than 51.19% of Java online submissions for Permutations.
java写代码好麻烦啊,本菜鸡准备学着用python来写了编程题了