给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {public List<List<Integer>> permute(int[] nums) {if (nums == null || nums.length == 0) return Collections.emptyList();List<List<Integer>> list = new ArrayList<>();boolean[] bs = new boolean[nums.length];int[] ns = new int[nums.length];flow(0, nums, bs, ns, list);return list;}public void flow(int cur, int[] nums, boolean[] bs, int[] ns, List<List<Integer>> list) {if (cur == nums.length) {List<Integer> tp = new ArrayList<>();for (int i : ns) {tp.add(i);}list.add(tp);} else {for (int i = 0; i < bs.length; i++) {if (!bs[i]) {ns[cur] = nums[i];bs[i] = true;flow(cur + 1, nums, bs, ns, list);bs[i] = false;}}}}}
最优解
class Solution {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);}}}作者:LeetCode-Solution链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/来源:力扣(LeetCode)著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
