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

相关推荐
阿昭L2 分钟前
leetcode旋转链表
算法·leetcode·链表
山楂树の2 分钟前
有效的括号(栈)
数据结构·算法
im_AMBER2 分钟前
Leetcode 81 【滑动窗口(定长)】
数据结构·笔记·学习·算法·leetcode
乾元7 分钟前
用 AI 做联动:当应用层出现问题,网络如何被“自动拉入决策回路”
运维·开发语言·网络·人工智能·ci/cd·自动化
xu_yule7 分钟前
算法基础(背包问题)-完全背包
c++·算法·动态规划·完全背包
x9766610 分钟前
使用 HMAC-SHA256算法对MCU UID进行加密
单片机·嵌入式硬件·算法
尘心cx10 分钟前
前端-APIs-day3
开发语言·前端·javascript
qq_124987075310 分钟前
基于springboot的智能医院挂号系统(源码+论文+部署+安装)
java·人工智能·spring boot·后端·毕业设计
gfdhy11 分钟前
【c++】素数详解:概念、定义及高效实现(判断方法 + 筛法)
开发语言·c++·算法·数学建模·ai编程
Dargon28812 分钟前
MATLAB的Simulink的While子系统(动作子系统)
开发语言·matlab·simulink·mbd软件开发