46. Permutations

    xiaoxiao2021-03-25  129

    Given a collection of distinct 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], [3,2,1] ]

    Subscribe to see which companies asked this question.

    public class Solution { static List<List<Integer>> permute(int[] nums) { List<List<Integer>> re = new ArrayList<List<Integer>>(); if (nums.length == 0) return re; back(nums.length, nums, 0, re); return re; } static void back(int length, int[] nums, int deep, List<List<Integer>> re) { if (deep == length) { List<Integer> temp = new ArrayList<Integer>(); for (int i : nums) temp.add(i); re.add(temp); return; } for (int t = deep; t < length; ++t) { swap(nums, deep, t); back(length, nums, deep + 1, re); swap(nums, deep, t); } } static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; return; } }

    转载请注明原文地址: https://ju.6miu.com/read-12803.html

    最新回复(0)