1. 程式人生 > >【leetcode】第46題 Permutations(遞迴法)題目+解析+程式碼

【leetcode】第46題 Permutations(遞迴法)題目+解析+程式碼

【題目】

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

        }
    }