46. 全排列
难度中等939收藏分享切换为英文接收动态反馈
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
通过次数204,324
提交次数265,348
题解
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
traceBack(nums, new LinkedList<Integer>(), res);
return res;
}
public void traceBack(int[] nums, LinkedList<Integer> temp,List<List<Integer>> res){
if( temp.size() == nums.length){
res.add( new LinkedList(temp)); //如果长度为nums.length 就添加
return;
}
for(int i =0; i < nums.length ; i++){
if( temp.contains(nums[i])){
continue;
}
temp.add(nums[i]); //将当前元素加入
traceBack( nums,temp, res); // 继续向后继续添加
temp.pollLast(); // 将刚添加的元素去除掉, 尝试新的元素
}
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 mym_74@163.com