给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

输入: [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

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. class Solution {
  2. public List<List<Integer>> permute(int[] nums) {
  3. if (nums == null || nums.length == 0) return Collections.emptyList();
  4. List<List<Integer>> list = new ArrayList<>();
  5. boolean[] bs = new boolean[nums.length];
  6. int[] ns = new int[nums.length];
  7. flow(0, nums, bs, ns, list);
  8. return list;
  9. }
  10. public void flow(int cur, int[] nums, boolean[] bs, int[] ns, List<List<Integer>> list) {
  11. if (cur == nums.length) {
  12. List<Integer> tp = new ArrayList<>();
  13. for (int i : ns) {
  14. tp.add(i);
  15. }
  16. list.add(tp);
  17. } else {
  18. for (int i = 0; i < bs.length; i++) {
  19. if (!bs[i]) {
  20. ns[cur] = nums[i];
  21. bs[i] = true;
  22. flow(cur + 1, nums, bs, ns, list);
  23. bs[i] = false;
  24. }
  25. }
  26. }
  27. }
  28. }

最优解

  1. class Solution {
  2. public List<List<Integer>> permute(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. List<Integer> output = new ArrayList<Integer>();
  5. for (int num : nums) {
  6. output.add(num);
  7. }
  8. int n = nums.length;
  9. backtrack(n, output, res, 0);
  10. return res;
  11. }
  12. public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
  13. // 所有数都填完了
  14. if (first == n) {
  15. res.add(new ArrayList<Integer>(output));
  16. }
  17. for (int i = first; i < n; i++) {
  18. // 动态维护数组
  19. Collections.swap(output, first, i);
  20. // 继续递归填下一个数
  21. backtrack(n, output, res, first + 1);
  22. // 撤销操作
  23. Collections.swap(output, first, i);
  24. }
  25. }
  26. }
  27. 作者:LeetCode-Solution
  28. 链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/
  29. 来源:力扣(LeetCode
  30. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。