LeetCode每日一题: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].

问题分析

数组全排列问题,典型的递归算法,每次交换两位数字递归生成所有的数组就行了。

代码实现

public ArrayList> permute(int[] num) {
        ArrayList> result = new ArrayList<>();
        if (num.length == 0) return result;
        permuteSwap(0, num, result);
        return result;
    }

    private void permuteSwap(int i, int[] num, ArrayList> result) {
        ArrayList list = new ArrayList<>();
        if (i == num.length) {
            for (int j = 0; j < num.length; j++) {
                list.add(num[j]);
            }
            result.add(list);
            return;
        }
        for (int j = i; j < num.length; j++) {
            int temp = num[i];
            num[i] = num[j];
            num[j] = temp;
            permuteSwap(i + 1, num, result);
            temp = num[i];
            num[i] = num[j];
            num[j] = temp;
        }
    }

你可能感兴趣的:(LeetCode每日一题:permutations)