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]]
难度:medium
题目:给定一组集合元素,返回其所有排列数。
思路:递归
Runtime: 3 ms, faster than 70.98% of Java online submissions for Permutations.
Memory Usage: 28 MB, less than 4.36% of Java online submissions for Permutations.class Solution { public List
> permute(int[] nums) { List
> result = new ArrayList<>(); permute(nums, 0, new Stack (), result); return result; } private void permute(int[] nums, int idx, Stack stack, List
> result) { if (idx == nums.length) { result.add(new ArrayList<>(stack)); return; } for (int i = idx; i < nums.length; i++) { stack.push(nums[i]); swap(nums, i, idx); permute(nums, idx + 1, stack, result); swap(nums, i, idx); stack.pop(); } } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; }}