LeetCode 046 Permutations

来源:互联网 发布:matlab哈密顿回路算法 编辑:程序博客网 时间:2024/05/16 10:47

题目描述

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

分析

这里写图片描述

代码

    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

0 0