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数组。

相关推荐
крон14 分钟前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan1 小时前
c++ 单例模式
开发语言·c++·单例模式
coderSong25681 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊1 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1181 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy2 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之2 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头3 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
年老体衰按不动键盘3 小时前
快速部署和启动Vue3项目
java·javascript·vue