这两天写几个递归算法题有点心得,记录一下
先说结论
递归过程:(判断条件)-进入--操作-(判断条件)-退出
| rec(a){ |
| if(满足退出)-退出 |
| 操作 |
| rec(a) |
| (操作) |
| } |
从链表逆序开始
| |
| public int length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(node.next, n) + 1; |
| |
| if (pos == n + 1) |
| node.next = node.next.next; |
| return pos; |
| } |
拆开
| |
| public int length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(node.next, n){...} + 1; |
| |
| }+ 1; |
| . |
| . |
| . |
| }+1 |
| |
| |
| |
| |
| if (pos == n + 1) |
| node.next = node.next.next; |
| return pos; |
| } |
达到出口条件
| |
| public int length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| int pos = length(node.next, n){... |
| if (node == null) |
| return 0; |
| int pos = length(ListNode node, int n) { |
| if (node == null) |
| return 0; |
| } + 1; |
| if (pos == n + 1) |
| node.next = node.next.next; |
| return pos; |
| |
| }+ 1; |
| . |
| . |
| . |
| }+1 |
| |
| |
| |
| |
| if (pos == n + 1) |
| node.next = node.next.next; |
| return pos; |
| } |
判断回文链表
| ListNode temp; |
| |
| public boolean isPalindrome(ListNode head) { |
| temp = head; |
| return check(head); |
| } |
| |
| private boolean check(ListNode head) { |
| if (head == null) |
| return true; |
| boolean res = check(head.next) && (temp.val == head.val); |
| temp = temp.next; |
| return res; |
| } |
| |
拆开
| ListNode temp; |
| |
| public boolean isPalindrome(ListNode head) { |
| temp = head; |
| return check(head); |
| } |
| |
| private boolean check(ListNode head) { |
| if (head == null) |
| return true; |
| boolean res = check(head.next){ |
| if (head == null) |
| return true; |
| boolean res = check(head.next){ |
| if (head == null) |
| return true; |
| boolean res = true && (temp.val == head.val); |
| temp = temp.next; |
| return res; |
| } && (temp.val == head.val); |
| temp = temp.next; |
| return res; |
| } && (temp.val == head.val); |
| temp = temp.next; |
| return res; |
| } |
| |
虽然这个题递归会重复计算一次,但是这个递归属于看得懂很难想出来
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 本地部署 DeepSeek:小白也能轻松搞定!
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 普通人也能轻松掌握的20个DeepSeek高频提示词(2025版)