版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/86996102
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]
]
dfs
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new LinkedList<>();
Set<Integer> set = new HashSet<>();
Arrays.sort(nums);
dfs(ans, new LinkedList<Integer>(), set, nums, nums.length);
return ans;
}
public void dfs(List<List<Integer>> ans, List<Integer> list, Set<Integer> set, int[] candidates, int target){
if (target == 0){
//ans.add(list); 又犯错误
ans.add(new LinkedList<Integer>(list));
return;
}else{
for (int i = 0; i<candidates.length; i++){
if (set.contains(candidates[i])) continue;
list.add(candidates[i]);
set.add(candidates[i]);
dfs(ans, list, set, candidates, target-1);
set.remove(candidates[i]);
list.remove(list.size()-1);
}
}
}
}