全排列-回溯

class Solution {
    public void back(int n,ArrayList<Integer> nums,List<List<Integer>> output,int first){
        if(first==n)output.add(new ArrayList<Integer>(nums));
        for(int i=first;i<n;i++){
            Collections.swap(nums,first,i);
            back(n,nums,output,first+1);
            Collections.swap(nums,i,first);
        }  
    }
    public List<List<Integer>> permute(int[] nums) {
        int n=nums.length;
        List<List<Integer>> output=new ArrayList();
        ArrayList<Integer> nums2=new ArrayList<Integer>();
        for(int num:nums){
            nums2.add(num);
        }
        back(n,nums2,output,0);
    return output;
    }
}

 

猜你喜欢

转载自www.cnblogs.com/NeverGiveUp0/p/11128400.html
今日推荐