46. Permutations (Medium)

https://leetcode.com/problems/permutations/

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Hints

Solutions

  • Java
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> rst = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return rst;
        }

        doPermutation(nums, rst, 0);

        return rst;
    }

    void swap(int[] nums, int x, int y) {
        int tmp = nums[x];
        nums[x] = nums[y];
        nums[y] = tmp;
    }

    private void doPermutation(int[] nums, List<List<Integer>> rst, int depth) {
        int len = nums.length;

        if (depth == len - 1) {
            List<Integer> solution = new ArrayList<>();
            for (int n : nums) {
                solution.add(n);
            }

            rst.add(solution);

            return;
        }

        for (int j = depth; j < len; j++) {
            swap(nums, depth, j);
            doPermutation(nums, rst, depth + 1);
            swap(nums, depth, j);
        }
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-21 20:10:06

results matching ""

    No results matching ""