Permutations(全排列)

问题

Given a list of numbers, return all possible permutations.

Notice

You can assume that there is no duplicate numbers in the list.

Have you met this question in a real interview? Yes
Example
For nums = [1,2,3], the permutations are:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

分析

使用递归来暴力解决。请参阅 Combinations(组合)

代码

public class Solution {
    /*
     * @param nums: A list of integers.
     * 
     * @return: A list of permutations.
     */
    public List> permute(int[] nums) {
        // write your code here
        List> res = new ArrayList<>();
        if (nums == null) {
            return res;
        }
        if (nums.length == 0) {
            res.add(new ArrayList());
            return res;
        }
        tree(nums, res, new ArrayList<>());
        return res;
    }

    private void tree(int[] nums, List> res, ArrayList arrayList) {
        if (arrayList.size() == nums.length) {
            res.add(new ArrayList(arrayList));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!arrayList.contains(nums[i])) {
                arrayList.add(nums[i]);
                tree(nums, res, arrayList);
                arrayList.remove(arrayList.size() - 1);
            }
        }
    }
}

你可能感兴趣的:(Permutations(全排列))