Jerry's Blog

Recording what I learned everyday

View on GitHub


19 August 2020

LeetCode(46) -- Permutations

by Jerry Zhang

Problem

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

Solution

以前做过这道题,今天试着自己写,还是有bug。下面重新整理一下答案的思路吧。

backtrack这个方法中,把所有元素都转化成list,参数中还包括元素的个数,以及开始的位置。然后分别对调每个字母都后面所有字母的位置,递归使用backtrack,最后再对调回来。

public class Permutation {

    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> output = new LinkedList<>();
        ArrayList<Integer> list = new ArrayList<>();
        for (int num : nums) {
            list.add(num);
        }
        int n = nums.length;
        backtrack(n, list, output, 0);
        return output;
    }

    public void backtrack(int n, ArrayList<Integer> nums, List<List<Integer>> output, int first) {
        if (first == n) {
            output.add(new ArrayList<>(nums));
        }
        for (int i = first; i < n; i++) {
            Collections.swap(nums, first, i);
            backtrack(n, nums, output, first + 1);
            Collections.swap(nums, first, i);
        }
    }

    public static void main(String[] args) {
        System.out.println(new Permutation().permute(new int[]{1, 2, 3}));
    }
}
tags: LeetCode