1.汉诺塔
题目解析
算法原理
为什么可以用递归
解决大问题的时候--出现了相同问题的子问题
解决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.合并两个有序链表
题目解析
算法原理
代码
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.反转链表
题目解析
算法原理
仅需做一次 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. 两两交互链表中的节点
题目解析
算法原理
代码
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)
题目解析
算法原理
代码
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;
}
}