标签:spl cli move color 需要 类型 div contains ++
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]); } } }
标签:spl cli move color 需要 类型 div contains ++
原文地址:https://www.cnblogs.com/immiao0319/p/13190182.html