LeetCode 046 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].

分析

《LeetCode 046 Permutations》

代码

    public List<List<Integer>> permute(int[] nums) {

        if (nums == null || nums.length == 0) {
            return new ArrayList<List<Integer>>();
        }

        ArrayList<List<Integer>> rt = new ArrayList<List<Integer>>();

        if (nums.length == 1) {
            rt.add(new ArrayList<Integer>(Arrays.asList(nums[0])));
        } else {

            for (int i = 0; i < nums.length; i++) {
                for (List<Integer> l : permute(resetof(nums, i))) {
                    l.add(nums[i]);
                    rt.add(l);
                }
            }
        }

        return rt;
    }

    private int[] resetof(int[] nums, int index) {

        int[] rt = new int[nums.length - 1];

        int s = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i != index) {
                rt[s++] = nums[i];
            }
        }

        return rt;
    }

参考网址

Permutations

    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/49778121
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞