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

回溯 leetcode

22. 括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1
输出:["()"]

提示:

  • 1 <= n <= 8
class Solution {public List<String> generateParenthesis(int n) {List<String> list=new ArrayList<>();String str="";fangfa(str,n,0,0,list);return list;}public void fangfa(String str,int n,int lcount,int rcount,List<String> list){if (lcount==n&&rcount==n){list.add(str);return;}if(lcount<rcount||lcount>n||rcount>n) return;//左fangfa(str+"(",n,lcount+1,rcount,list);//右fangfa(str+")",n,lcount,rcount+1,list);}
}

46. 全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:

输入:nums = [1]
输出:[[1]]

提示:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数 互不相同
class Solution {List<List<Integer>> list=new ArrayList<List<Integer>>();public List<List<Integer>> permute(int[] nums) {b(0,nums);return list;}public void b(int t,int[] x){if(t>=x.length){List<Integer> l=new ArrayList<>();for (int i = 0; i < x.length; i++) {l.add(x[i]);}list.add(l);}else {for (int i = t; i < x.length; i++) {// swap(x[t],x[i]);int temp=x[t];x[t]=x[i];x[i]=temp;b(t+1,x);// swap(x[t],x[i]);temp=x[t];x[t]=x[i];x[i]=temp;}}}
}

无剪枝条件、递归

 

http://www.lryc.cn/news/354255.html

相关文章:

  • Android firebase消息推送集成 FCM消息处理
  • react中怎么为props设置默认值
  • 企业如何做好 SQL 质量管理?
  • 半年不在csdn写博客,总结一下这半年的学习经历,coderfun的一些碎碎念.
  • c++中的命名空间与缺省参数
  • SpringBoot整合WebSocket实现聊天室
  • llama-factory学习个人记录
  • VLC播放器(全称VideoLAN Client)
  • 跟小伙伴们说一下
  • 学 C/C++ 具体能干什么?
  • Django之Ajax实战笔记--城市级联操作
  • 基于Netty实现WebSocket服务端
  • 27【Aseprite 作图】盆栽——拆解
  • 【开源】2024最新python豆瓣电影数据爬虫+可视化分析项目
  • [JDK工具-5] jinfo jvm配置信息工具
  • 【Linux系统编程】进程概念、进程排队、进程标识符、进程状态
  • Java与GO语言对比分析
  • Linux文件系统原理
  • 初识Spring Cache:如何简化你的缓存处理?
  • 攻防世界[GoodRe]
  • IntelliJ IDEA实用插件:轻松生成时序图和类图
  • SpringBoot + Mybatis-Plus中乐观锁实现
  • 设计模式深度解析:分布式与中心化,IT界两大巨头“华山论剑”
  • 转行一年了
  • 【LeetCode 151】反转字符串中的单词
  • Behind the Code:Polkadot 如何重塑 Web3 未来
  • for循环里如果std::pair的类型写不对,可能会造成性能损失
  • 【Linux】Linux的基本指令_2
  • Effective C++(3)
  • 自定义RedisTemplate序列化器