LeetCode:第46题 全排列

(一)题目描述:

给定一个没有重复数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

(二)思路分析:

  1 先将第一个数固定住,然后对后面的所有数字进行全排列

  2 将第二个数字放到第一个位置上,在对第一个之后的数字进行全排列

  3 如此下去,直到start在末尾位置,只对末尾一个值排列

  LeetCode  AC代码

public class Solution {
    // 最终返回的结果集
    static List<List<Integer>> res = new ArrayList<List<Integer>>();
    public static List<List<Integer>> permute(int[] nums) {
        int len = nums.length;
        if (len==0||nums==null)  return res;

        // 采用前后元素交换的办法,dfs解题
        exchange(nums, 0, len);
        return res;
    }

    public static void exchange(int[] nums, int i, int len) {
        // 将当前数组加到结果集中
        if(i==len-1) {
            List<Integer> list = new ArrayList<>();
            for (int j=0; j<len; j++){
                list.add(nums[j]);
            }
            res.add(list);
            return ;
        }
        // 将当前位置的数跟后面的数交换,并搜索解
        for (int j=i; j<len; j++) {
            swap(nums, i, j);
            exchange(nums, i+1, len);
            swap(nums, i, j);
        }
    }
    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
}

   


(三)递归实现

public class Test {
    public static void main(String[] args) {
        int[] a = {1,2,3};
        //对0位置开始的所有值全排列
        f(a, 0);
    }
    private static void f(int[] a, int start) {
        /*    start
         *     |
         *     1,2,3
         *     i 
         *     *)在start位置,固定一个值
         *     *)对start+1后面的值全排列
         */
        //最简问题
        //start在末尾位置,只对末尾一个值排列
        if(start==a.length-1) {
            System.out.println(Arrays.toString(a));
            return;
        }
        for(int i=start; i<a.length; i++) {
            //i和start位置交换
            swap(a, i, start);
            f(a, start+1);//递归对start+1之后的值全排列
            //再交换回来,否则会引起数据混乱
            swap(a, i, start);
        }
    }
    private static void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

猜你喜欢

转载自www.cnblogs.com/misscai/p/9927157.html