28.递归、搜索、回溯之递归2

1.汉诺塔

. - 力扣(LeetCode)

题目解析

算法原理

为什么可以用递归

解决大问题的时候--出现了相同问题的子问题

解决N=4出现N=3的情况

如何编写递归的代码

挖掘出重复的子问题--函数头

只关心某一个子问题在做什么--函数体

递归的出口

代码

class Solution {
    public void hanota(List<Integer> a, List<Integer> b, List<Integer> c) {
        dfs(a, b, c, a.size());
    }

    public void dfs(List<Integer> a, List<Integer> b, List<Integer> c, int n) {
        if (n == 1) {
            c.add(a.remove(a.size() - 1));
            return;
        }
        dfs(a, c, b, n - 1);
        c.add(a.remove(a.size() - 1));
        dfs(b, a, c, n - 1);
    }
}

细节问题---是a的最后一个元素

2.合并两个有序链表 

21. 合并两个有序链表 - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        if (l1.val <= l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}

3.小总结 

只有一个分支改成循环很容易 

4.反转链表

. - 力扣(LeetCode)

题目解析

算法原理

 

仅需做一次 dfs 即可
后序遍历 

代码

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

5. 两两交互链表中的节点

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode tmp = swapPairs(head.next.next);
        ListNode ret = head.next;
        ret.next = head;
        head.next = tmp;
        return ret;
    }
}

6. Pow(x, n)- 快速幂(medium)

. - 力扣(LeetCode)

题目解析

算法原理

 

代码

class Solution {
    public double myPow(double x, int n) {
        return n < 0 ? 1.0 / pow(x, -n) : pow(x, n);
    }

    public double pow(double x, int n) {
        if (n == 0)
            return 1.0;
        double tmp = pow(x, n / 2);
        return n % 2 == 0 ? tmp * tmp : tmp * tmp * x;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值