【leetcode】第46题 Permutations(递归法)题目+解析+代码

来源:互联网 发布:天盾苹果手机数据恢复软件 编辑:程序博客网 时间:2024/06/05 09:36

【题目】

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]]

【解析】

这个题目就是练习全排列的题目,这里用的递归法,非递归法参照47题即可解答。

【代码】

public static List<List<Integer>> permute(int[] nums) {        LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();        prem(res,nums,0,nums.length-1);        return res;    }    public static void swap(int[] nums,int p,int q){        int temp=nums[p];        nums[p]=nums[q];        nums[q]=temp;    }    public static void prem(List<List<Integer>> res,int[] nums,int p,int q){        if(p==q){            List<Integer> tempList = new ArrayList<Integer>();            for(int b:nums)                tempList.add(b);            res.add(tempList);        }        else{            for(int i=p;i<nums.length;i++)            {                swap(nums,p,i);                prem(res,nums,p+1,q);                swap(nums,p,i);            }        }    }



阅读全文
0 0