版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1. 斐波那切 (爬楼梯)
class Solution {
HashMap<Integer,Integer> cache = new HashMap<>();
public int fib(int N) {
if (cache.containsKey(N)) {
return cache.get(N);
}
int result;
if (N < 2) {
result = N;
}else {
result = fib(N-1) + fib(N-2);
}
cache.put(N,result);
return result;
}
}
2. 合并2个有序链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode pre = new ListNode(Integer.MIN_VALUE);
if (l1.val < l2.val) {
pre.next = l1;
l1.next = mergeTwoLists(l1.next,l2);
}else {
pre.next = l2;
l2.next = mergeTwoLists(l1,l2.next);
}
return pre.next;
}
}
3. 反转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
return helper(cur,prev);
}
public ListNode helper(ListNode cur, ListNode prev) {
if (cur == null) return prev;
ListNode next = cur.next;
cur.next = prev;
return helper(next,cur);
}
}
4. 二叉树最大深度
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
};