Jerry's Blog

Recording what I learned everyday

View on GitHub


26 December 2019

LeetCode(26) -- 22, 23

by Jerry Zhang

P22. 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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Solution

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        backtrack(ans, "", 0, 0, n);
        return ans;
    }
    
    public void backtrack (List<String> ans, String cur, int open, int close, int max) {
        if (cur.length() == max * 2) {
            ans.add(cur);
            return;
        }

        if (open < max) {
            backtrack(ans, cur + "(", open + 1, close, max);
        }
        if (close < open) {
            backtrack(ans, cur + ")", open, close + 1, max);
        }
    }
}

P23. Merge k Sorted Lists (Hard)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

My Solution

public class P23_MergekSortedLists {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        PriorityQueue<ListNode> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
        for (ListNode node : lists) {
            if (node != null) {
                pq.offer(node);
            }
        }
        while (pq.size() > 0) {
            ListNode node = pq.poll();
            cur.next = node;
            cur = cur.next;
            if (node.next != null) {
                pq.offer(node.next);
            }
        }
        return dummy.next;
    }
}

33%

The Best Solution

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0)
            return null;
        return mergeKListsCD(lists, 0, lists.length-1);
    }
    private ListNode mergeKListsCD(ListNode[] lists, int m, int n){
        if (m == n) {
            return lists[m];
        }
        ListNode left = mergeKListsCD(lists, m, (m+n)/2);
        ListNode right = mergeKListsCD(lists, (m+n)/2+1, n);
        return merge(left, right);
    }
    private ListNode merge(ListNode left, ListNode right) {
        ListNode start = new ListNode(-1);
        ListNode cur = start;
        while (left != null && right != null) {
            if (left.val < right.val) {
                cur.next = left;
                left = left.next;
            } else {
                cur.next = right;
                right = right.next;
            }
            cur = cur.next;
        }
        cur.next = (left == null) ? right : left;
        return start.next;
    }
}

Divide and Conquer. Merge two lists at a time.

tags: LeetCode