典型的dp,注意點的程序中已經標出:java
public class Solution { //State: Sort envelopes' width, f[i] is maximum number of envelopes number i envelope can get; //Function: f[i] = Math.max(f[i - k] + 1) if Size(i - k) < size(i); //Initialize: f[i] = 1; //Result: Max(f[i]); public int maxEnvelopes(int[][] envelopes) { if (envelopes == null || envelopes.length == 0 || envelopes[0].length == 0) { return 0; } //按信封的width先排個序,方便後面的計算 Arrays.sort(envelopes, new Comparator<int[]>() { public int compare(int[] x, int[] y) { return x[0] - y[0]; } }); int[] f = new int[envelopes.length]; //這裏全部的一個信封均可以獨立地表示包含一個信封,因此初始化值爲1 Arrays.fill(f, 1); int result = 0; for (int i = 0; i < envelopes.length; i++) { for (int k = i - 1; k >= 0; k--) { //由於array.sort後,還會存在width相同的狀況,因此操做以前要先判斷width是否是嚴格小於現有的信封 if (envelopes[k][0] < envelopes[i][0] && envelopes[k][1] < envelopes[i][1]) { f[i] = Math.max(f[i], f[k] + 1); } } result = Math.max(result, f[i]); } return result; } }