当前位置: 首页 > news >正文

回溯算法——排列篇

目录

一、全排列

二、全排列II


一、全排列

46. 全排列 - 力扣(LeetCode)

class Solution {List<List<Integer>> result=new ArrayList<>();LinkedList<Integer> path=new LinkedList<>();boolean[] used;public List<List<Integer>> permute(int[] nums) {used=new boolean[nums.length];backtracking(nums);return result;}public void backtracking(int[] nums){if(path.size()==nums.length){result.add(new ArrayList<>(path));return;}for(int i=0;i<nums.length;i++){if(used[i])continue;used[i]=true;path.add(nums[i]);backtracking(nums);path.removeLast();//移除最后一个添加的元素used[i]=false;//元素修改为未使用}}
}

二、全排列II

47. 全排列 II - 力扣(LeetCode)

class Solution {List<List<Integer>> result=new ArrayList<>();List<Integer> path=new ArrayList<>();public List<List<Integer>> permuteUnique(int[] nums) {boolean[] used=new boolean[nums.length];Arrays.fill(used,false);Arrays.sort(nums);backtracking(nums,used);return result;}public void backtracking(int[] nums,boolean[] used){if(path.size()==nums.length){result.add(new ArrayList<>(path));return;}for(int i=0;i<nums.length;i++){if(i>0&&nums[i]==nums[i-1]&&used[i-1]==true)continue;if(used[i]==false){used[i]=true;path.add(nums[i]);backtracking(nums,used);path.removeLast();used[i]=false;}}}
}

相关文章:

  • 阿里云ecs 8核 16G 内存 装有redis6 分配了3G内存,和2个tomcat 每个tomcat 4G 服务器反应迟钝,如何确认不是redis的问题
  • web.py使用时报错AttributeError: No template named image_window
  • RTMP协议解析【二】
  • 下一代电子电气架构(EEA)的关键技术
  • 运行时runtime是什么?(程序在运行过程中所依赖的环境、资源管理机制以及动态行为的总和)(包括内存分配、异常处理、线程调度、类型检查、资源访问等)
  • RAG知识库SentenceSplitter分段问题分析与优化方案
  • 操作系统理解(xv6)
  • NC028NQ472美光固态颗粒NQ484NQ485
  • 第五章 GPT模块配置
  • centos系统redis-dump安装
  • FPGA开发全流程
  • bitbar环境搭建(ruby 2.4 + rails 5.0.2)
  • MCU 上电不启动的常见原因分析与排查思路
  • Transformer到底解决什么问题?
  • R语言速查表
  • 【Django】Django DRF 中如何手动调用分页器返回分页数据(APIView,action场景)
  • Windows系统编译GSL与VS2022联合编程
  • 从零基础到最佳实践:Vue.js 系列(3/10):《组件化开发入门》
  • 链表day3
  • 【初识】内网渗透——基础概念,基本工具使用
  • 网站开发项目实战/品牌广告语经典100条
  • 自学程序员的步骤/搜索引擎优化效果
  • 在哪些网站可以做企业名称预审/文明seo
  • 攻略做的比较好的网站/百度推广登录平台官网
  • 最先进的深圳网站建设/汽车网络营销的方式有哪些
  • 动漫人物做羞羞事的网站/泉州百度搜索推广