LC Divide & Conquer Summary

把问题划分为求子问题,向merge sort,Binary Search这些都可以看成是这类问题,

有些:考虑最后一步怎么样怎么样,然后把大问题划分为几个无不干扰的子问题

有些:用Heap保存K个子问题的解也可以看出这类问题,比如:


23. Merge k Sorted Lists

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

package l23;

import java.util.Comparator;
import java.util.PriorityQueue;

/*
 * heap
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
    	if(lists.length == 0)	return null;
        PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>(){
			public int compare(ListNode o1, ListNode o2) {
				return o1.val - o2.val;
			}
        });
        
        for(ListNode r : lists)	{
        	if(r != null)
        		pq.add(r);
        }
        
        ListNode dummy = new ListNode(0), t = dummy;
        while(!pq.isEmpty()) {
        	ListNode r = pq.remove();
        	if(r == null)	continue;
        	t.next = r;
        	t = t.next;
        	if(r.next != null)	pq.add(r.next);
        }
        
        return dummy.next;
    }
}

218. The Skyline Problem( 把问题划分为start point & end point

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

Buildings Skyline Contour

The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]

package l218;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/*
 * 之前是直接抄DisCuss里面答案,也没看懂,今天在youtube上看了别人的视频
 * 总算看懂了,youtube竟然有这么好的资源
 * 
 * idea:一直水平往右移动,同时看y坐标,要么上升,要么下降
 * 			维持一个最大堆,每次最大堆中的max变化时,对应的时刻就是要输出某个keypoint的时间点(想想对应的几何拓扑)
 * 如果遇到的是building的起始节点,就把数据(高度信息)插入到堆
 * 如果是building的结束节点,就把数据移除堆
 * 在这些过程中检测max的变换
 * 
 * Heap删除复杂度O(N),可以通过TreeMap优化
 */
public class Solution {
    public List<int[]> getSkyline(int[][] buildings) {
    	List<int[]> ret = new ArrayList<int[]>();
        List<int[]> l = new ArrayList<int[]>();
        for(int[] b : buildings) {
        	l.add(new int[]{b[0], -b[2]}); //用负的高度记录start
        	l.add(new int[]{b[1], b[2]});  // 正的高度表示end
        }
        
        Collections.sort(l, new Comparator<int[]>(){
			/* 
			 * 先按照x坐标排,相同就按照高度排
			 * 1. 如果是start,当几个节点的x坐标一样时,因为高度是负的,所以高的排在前面,
			 * 			这样高的先加到最大堆并且可能输出该节点,而后面那个高度低一点的就输出不了了
			 * 2. 如果是end,高度是正的,高的在后面,前面小的高度删除时不会影响最大值(因为后面那个就比它的高度大),
			 * 			所以不输出
			 * 
			 * 而1,2这两种corner case都是符合题意的
			 */
			public int compare(int[] o1, int[] o2) {
				if(o1[0] != o2[0])
					return o1[0] - o2[0];
				return o1[1] - o2[1];
			}
        });
        
        /*
         * PriorityQueue最大堆用来保存遍历过程中overlap的高度
         * 记录当前的max和更新操作后的max
         * 最开始初始化堆时加入一个0垫底
         */
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(128, new Comparator<Integer>(){

			@Override
			public int compare(Integer o1, Integer o2) {
				return o2-o1;
			}
        	
        });
        
        
        int preMax = 0;
        pq.offer(0);		 
        for(int[] b : l) {
        	if(b[1] < 0) {
        		pq.offer(-b[1]);
        	} else {
        		pq.remove(b[1]);
        	}
        	
        	// 如果前后max变了,说明keypoint出现了
        	if(preMax != pq.peek()) {
        		ret.add(new int[]{b[0], pq.peek()});	// keypoint高度就是堆当前的max
        		preMax = pq.peek();	
        	}
        }
        
        return ret;
    }
}

241. Different Ways to Add Parentheses( 典型的最后一个怎么样怎么样的问题,表达式问题。。。

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.


Example 1

Input: "2-1-1".

((2-1)-1) = 0
(2-(1-1)) = 2

Output: [0, 2]


Example 2

Input: "2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10

Output: [-34, -14, -10, -10, 10]

package l241;

import java.util.ArrayList;
import java.util.List;

/*
 * 因为不需要求出加括号的字符串形式,那感觉这种加括号的问题可以用Divide & Conquer
 * 考虑最后一次运算的运算符
 */
public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
    	List<Integer> ret = new ArrayList<Integer>();
    	
    	if(input.indexOf('+')==-1 && input.indexOf('-')==-1 && input.indexOf('*')==-1) {
    		ret.add(Integer.valueOf(input));
    		return ret;
    	}
    	
    	
    	for(int i=1; i<input.length(); i++) {
    		if(input.charAt(i) == '+') {
    			List<Integer> l = diffWaysToCompute(input.substring(0, i));
    			List<Integer> r = diffWaysToCompute(input.substring(i+1));
    			for(int p : l)	for(int q: r)	ret.add(p+q);
    		} else if(input.charAt(i) == '-') {
    			List<Integer> l = diffWaysToCompute(input.substring(0, i));
    			List<Integer> r = diffWaysToCompute(input.substring(i+1));
    			for(int p : l)	for(int q: r)	ret.add(p-q);
    		} else if(input.charAt(i) == '*') {
    			List<Integer> l = diffWaysToCompute(input.substring(0, i));
    			List<Integer> r = diffWaysToCompute(input.substring(i+1));
    			for(int p : l)	for(int q: r)	ret.add(p*q);
    		}
    	}
    	
    	return ret;
    }
}


315. Count of Smaller Numbers After Self(利用Merge Sort过程中部分数组有序

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Return the array [2, 1, 1, 0].


327. Count of Range Sum(Merge类似问题的变形,想想怎么转化

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.

Example:
Given nums = [-2, 5, -1]lower = -2upper = 2,
Return 3.
The three ranges are : [0, 0][2, 2][0, 2] and their respective sums are: -2, -1, 2.



312. Burst Balloons(最后burst哪个气球然后划分子问题

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note: 
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Given [3, 1, 5, 8]

Return 167

    nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
   coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167
/*
 * 最直观的考虑就是第一个burst哪个,然后接着考虑下一个burst的位置
 * 但是这样感觉没有止境,就像之前的241. Different Ways to Add Parentheses一样
 * 那考虑某一个balloons为最后一个burst的,分治左右两边求最大
 * 因为要burst子数组的时候后要用到Boundary,所以先对nums扩容
 */
public class Solution {
	
	int[][] memory;
	
    public int maxCoins(int[] nums) {
    	int[] A = new int[nums.length+2];
    	A[0] = 1; A[A.length-1] = 1;
    	for(int i=1; i<A.length-1; i++)	A[i]=nums[i-1];
    	memory = new int[A.length][A.length];
        return maxCoins(A, 1, A.length-2);
    }

	private int maxCoins(int[] nums, int i, int j) {
		if(i > j)	return 0;
		if(memory[i][j] != 0)	return memory[i][j];
		
		int max = 0;
		for(int k=i; k<=j; k++) {
			int left = maxCoins(nums, i, k-1);
			int right = maxCoins(nums, k+1, j);
			max = Math.max(max, left+right+nums[i-1]*nums[k]*nums[j+1]);
		}
		
		memory[i][j] = max;
		return max;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值