您的位置:首页 > 其它

LeetCode 046 Permutations

2015-11-11 10:00 393 查看

题目描述

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

分析



代码

[code]    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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: