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

相关推荐
zhangjw342 小时前
第29篇:Java伪共享与对象分配:并发性能优化的关键
java·开发语言·性能优化
可编程芯片开发2 小时前
基于simulink的PEM燃料电池控制系统建模与仿真,对比PID,积分分离以及滑模控制器
算法
宠友信息2 小时前
内容社区源码多端数据协议与 Spring Boot 状态流转实现思路
java·spring boot·websocket·uni-app
学究天人2 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷2)
算法·数学建模·动态规划·图论·抽象代数·拓扑学
Java面试题总结3 小时前
Python 开发技巧 · 高级装饰器 —— 从基础到工业级实战
开发语言·python
一路向北North3 小时前
Spring Security OAuth2.0(19):JWT令牌
java·后端·spring
玛卡巴卡ldf3 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
wanzehongsheng3 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
一叶飘零_sweeeet4 小时前
IDEA 插件 Trae AI 最新全攻略(基于 TRAE AI: Coding Assistant 1.7.0.0)
java·intellij-idea·trae
liulilittle4 小时前
Exhaustive drift-fix simulation V2 — KCC on shared-bottleneck wired path.
开发语言·网络·python·tcp/ip·计算机网络·信息与通信·通信