[leedcode 46] Permutations

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;
    }
}

 

你可能感兴趣的:(code)