全排列 leetcode第46题
题目如下(该题在剑指offer中也有,比较经典):

思路:很典型的回溯算法题.可以直接套框架,
- 逻辑就是最前面的值依次和后面的值交换,然后第二个值再依次和后面的值交换,依次递归到末尾
注意:什么时候能加入到最后的list中? index代表遍历节点的下标,
- 只有当index==nums.length-1时,才能加入到list中,为什么?
因为前面的交换只是列举出所有可能的值,只有交换到最后的时候,一种情况才算完成,不然会有重复值.
代码如下:
class Solution {
private List<List<Integer>> list=new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums==null||nums.length==0) return list;
//将数组转换成列表
ArrayList<Integer> nums_lst=new ArrayList<>();
for(int i=0;i<nums.length;i++){
nums_lst.add(nums[i]);
}
backtrack(nums_lst,0);
return list;
}
public void backtrack(ArrayList<Integer> nums_lst,int index){
//一次情况完成,加入到list中
if(index==nums_lst.size()-1){
list.add(new ArrayList<Integer>(nums_lst));
}
for(int i=index;i<=nums_lst.size()-1;i++){
Collections.swap(nums_lst,index,i);
backtrack(nums_lst,index+1);
Collections.swap(nums_lst,index,i);
}
}
}
本文详细解析了LeetCode第46题全排列的经典解法,采用回溯算法实现,通过交换元素位置来生成所有可能的排列组合,避免重复值,最终得到所有全排列结果。
484

被折叠的 条评论
为什么被折叠?



