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

相关推荐
努力搬砖的咸鱼几秒前
API 网关:微服务的大门卫
java·大数据·微服务·云原生
蓑衣夜行1 分钟前
QtWebEngine 自动重启方案
开发语言·c++·qt·web·qwebengine
爱喝热水的呀哈喽3 分钟前
chns方程 推导简单的能量耗散律,分部积分向量形式,sav初简介
算法
lsx2024065 分钟前
XQuery 实例详解
开发语言
代码游侠6 分钟前
应用——统计文件字符数、单词数、行数
服务器·笔记·算法
hefaxiang6 分钟前
猜数字小游戏--用分支和循环实现
c语言·开发语言
小清兔8 分钟前
一个unity中URP的环境下旋转天空盒的脚本(RotationSky)
开发语言·数据库·学习·程序人生·unity·c#·游戏引擎
小裕哥略帅10 分钟前
Springboot中全局myBaits插件配置
java·spring boot·后端
岁岁的O泡奶11 分钟前
NSSCTF_crypto_[MTCTF 2021 final]ezRSA
经验分享·python·算法·密码学·crypto
San30.12 分钟前
从原型链到“圣杯模式”:JavaScript 继承方案的演进与终极解法
开发语言·javascript·原型模式