problem 21,22,23
21. Merge Two Sorted Lists
Easy
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
1 | |
注意边界的判断,这个题目可以以一个链表为基础,这样就只需要$O(1)$的空间
也可以新建一个链表,这样略快一点,需要$O(m+n)$空间
1 | |
22. Generate Parentheses
Medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
1 | |
这个题可以理解为一个条件二叉树,很明显可以用一个深度优先搜索来做,于是就会有一个递归的算法
1 | |
也可以采用广度优先搜索来做,不过带条件的搜索最好用两个队列或者字典来实现
1 | |
代码很简单,键值表达的意思是左括号的数量,通过循环的数量可以算出右括号的数量i+1-ke,这样可以很轻松的遍历所有的情况
23. Merge k Sorted Lists
Hard
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
1 | |
1 | |