46. Permutations 全排列
Posted immiao0319
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了46. Permutations 全排列相关的知识,希望对你有一定的参考价值。
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]
]
List<Integer>的大小是size()
permutations,remove的是最后一位。(permutations.size() - 1);
nums数组为空时,应该是[[]]的结果。需要results.add(new ArrayList<>(permutations));
回溯法helper的返回类型应该是void
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> results = new ArrayList<>(); List<Integer> permutation = new ArrayList<>(); HashSet<Integer> set = new HashSet<>(); //2种cc if (nums == null) { return null; } if (nums.length == 0) { results.add(new ArrayList<Integer>()); return results; } helper(nums, permutation, set, results); return results; } public void helper(int[] nums, List<Integer> permutation, HashSet<Integer> set, List<List<Integer>> results) { //cc if (permutation.size() == nums.length) { results.add(new ArrayList(permutation)); return ; } for (int i = 0; i < nums.length; i++) { if (set.contains(nums[i])) { continue; } set.add(nums[i]); permutation.add(nums[i]); helper(nums, permutation, set, results); permutation.remove(permutation.size() - 1); set.remove(nums[i]); } } }
以上是关于46. Permutations 全排列的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 46. 全排列(Permutations)