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

相关推荐
jimy11 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743871 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php
hhb_6181 小时前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
朝朝辞暮i2 小时前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法
小凡geo2 小时前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
朝朝辞暮i2 小时前
C++ 第 4 课:if / else —— 让程序自己做决定
开发语言·c++
苏打豆2 小时前
Pinocchio源码阅读——刚体运动物理量空间变换及求导
c++·线性代数·算法·矩阵·机器人
波力海苔夹心脆6752 小时前
C# 值类型与引用类型详解:存储位置、赋值机制、参数传递、相等比较、装箱拆箱与常见陷阱
开发语言·jvm·经验分享·笔记·c#·.net
蜗牛互联网3 小时前
WSL Containers GA:本地AI容器的生命周期、网络与治理验收
java·网络·人工智能·后端
m0_380743873 小时前
Qt中导航栏实现的详细指南
开发语言·c++