54 回溯算法求解全排列问题

问题描述:给定一个没有重复数字的序列nums,返回其所有可能的全排列。

回溯算法求解:最多进行nums.length次深度的dfs递归,每一次都从剩下未选择序列里面选取一个进行递归,使用used数组进行保存当前是否选取;

java 复制代码
public void  tranceBack(int []nums,int used[],int index,LinkedList<Integer>templist,LinkedList<LinkedList<Integer>>res)
{
if(index==nums.length){
res.add(templist);
return ;
}
for(int i=0;i<nums.length;i++)
{
if(used[i])
{
continue;
}else
{
used[i]=true;
templist.add(nums[i]);
tranceBack(nums,used,index+1,templist,res);
used[i]=false;
templist.remove(templist.size()-1);
}
}
}
public List<List<Integer>>TranceBack(int [] nums)
{
List<List<Integer>>res=new LinkedList<LinkedList<Integer>>();
Boolean [] used=new Boolean[nums.length];
tranceBack(nums,used,new LinkedList<Integer>(),res);
​​​​​​​return res;
}

而对于所有子集而言,每一次递归都保存一次结果,for循环从index开始,不需要used数组。

相关推荐
我是伪码农3 分钟前
11.21程序设计
数据结构·算法
zbguolei5 分钟前
第002篇 · 战火中的电子黎明
开发语言·php
IManiy5 分钟前
AgentScope Java 2.0(四)上下文、状态与中间件
java
sean_wang1212 分钟前
Rust 轻量级虚拟机 smolvm 实战:200ms 冷启动、OCI 镜像直跑、单文件打包
开发语言·后端·rust·大鲸华章
Tisfy1 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
青山木1 小时前
JVM 类加载全解:Class 文件结构、加载链接初始化与双亲委派
java·jvm·后端·类加载·双亲委派机制
羊在吃青草1 小时前
C语言之数组
c语言·数据结构
郝学胜-神的一滴1 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
灯澜忆梦1 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法