您的位置:首页 > 其它

[leedcode 46] Permutations

2015-07-11 11:03 239 查看
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]
.

public class Solution {
//全排列:构造一个递归函数,函数的参数一个代表开始排列的索引,一个代表最终排列的索引
//每一位与开始位进行交换,再递归start+1到end,注意结果的保存
List<Integer> seq;
List<List<Integer>> res;
public List<List<Integer>> permute(int[] nums) {
seq=new ArrayList<Integer>();
res=new ArrayList<List<Integer>>();
findpermute(nums,0,nums.length-1);
return res;

}
public void findpermute(int []nums,int start,int end){
if(start>end){
res.add(new ArrayList<Integer>(seq));//注意要重新new一个
return ;
}

for(int i=start;i<=end;i++){
swap(nums,start,i);
seq.add(nums[start]);
findpermute(nums,start+1,end);
seq.remove(seq.size()-1);//注意删除
swap(nums,start,i);
}
}
public void swap(int[] nums,int i,int j){
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: