题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Java代码:
class Solution {
public List<List<Integer>> permute(int[] nums) {
Map<Integer,Integer> book = new HashMap<>();
List<List<Integer>> res = new ArrayList<>();
dfs(nums,0,book,res,new ArrayList<>());
return res;
}
private void dfs(int[] nums, int step, Map<Integer,Integer> book, List<List<Integer>> res, List<Integer> tmpList){
if (step == nums.length){
//全都试完了
res.add(new ArrayList<>(tmpList));
return;
}
for (int i =0;i<nums.length;i++){
int cur = nums[i];
if (book.get(cur) == null){
book.put(cur,1);//标记用过
tmpList.add(cur);
dfs(nums,step+1,book,res,tmpList);
book.remove(cur);//取消标记
tmpList.remove(tmpList.size() - 1);
}
}
}
}











网友评论