46. 全排列 Permutations
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
方法 :
回溯法。
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> output = new ArrayList<Integer>(); for (int num : nums) { output.add(num); } int n = nums.length; backtrack(n, output, res, 0); return res; } public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) { if (first == n) { res.add(new ArrayList<Integer>(output)); } for (int i = first; i < n; i++) { Collections.swap(output, first, i); backtrack(n, output, res, first + 1); Collections.swap(output, first, i); } }
参考链接:
https://leetcode.com/problems/permutations/
https://leetcode-cn.com/problems/permutations/