Repository navigation
Expand file tree
/
Copy pathDp.tex
More file actions
2278 lines (1621 loc) · 59.6 KB
/
Copy pathDp.tex
File metadata and controls
2278 lines (1621 loc) · 59.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Dynamic Programing}
\section{House Robber} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
\subsubsection{Solution I}
\begin{Code}
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
// dp意思是统计到当前房子为止的最大收益
int[] dp = new int[n];
// 这里要注意越界的问题
for (int i = 0; i < n; i++) {
dp[i] = Math.max(nums[i] + (i > 1 ? dp[i - 2] : 0), i > 0 ? dp[i - 1] : 0);
}
return dp[n - 1];
}
\end{Code}
\subsubsection{Solution II}
\begin{Code}
// 这个简洁
public int rob2(int[] nums) {
int prev = 0, cur = 0;
for (int n : nums) {
int temp = cur;
cur = Math.max(n + prev, cur);
prev = temp;
}
return cur;
}
\end{Code}
\newpage
\section{House Robber II} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
\textbf{Note:} This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
\subsubsection{Solution}
\begin{Code}
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
} else if (n == 1) {
return nums[0];
}
// 包含第一个就不能包含最后一个,包含最后一个就不能包含第一个
return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1));
}
private int rob(int[] nums, int start, int end) {
int prev = 0, cur = 0;
for (int i = start; i <= end; i++) {
int temp = cur;
cur = Math.max(nums[i] + prev, cur);
prev = temp;
}
return cur;
}
\end{Code}
\newpage
\section{Best Time to Buy and Sell Stock} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
\textbf{Example 1:}
\textbf{Input:} [7, 1, 5, 3, 6, 4]
\textbf{Output:} 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
\textbf{Example 2:}
\textbf{Input:} [7, 6, 4, 3, 1]
\textbf{Output:} 0
In this case, no transaction is done, i.e. max profit = 0.
\subsubsection{Solution}
\begin{Code}
/**
* 注意这里maxProfit别初始化为Integer.MIN_VALUE,
* 因为不一定要交易的,至少不亏钱
*/
public int maxProfit(int[] prices) {
int maxProfit = 0, min = Integer.MAX_VALUE;
for (int price : prices) {
int profit = price - min;
if (profit > maxProfit) {
maxProfit = profit;
}
min = Math.min(min, price);
}
return maxProfit;
}
\end{Code}
\newpage
\section{Best Time to Buy and Sell Stock II} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
\subsubsection{Solution}
\begin{Code}
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
\end{Code}
\newpage
\section{Best Time to Buy and Sell Stock III} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
\textbf{Note:}
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
\subsubsection{Solution}
\begin{Code}
public int maxProfit(int[] prices) {
int len = prices.length;
if (len == 0) {
return 0;
}
int min = prices[0];
int[] left = new int[len];
for (int i = 1; i < len; i++) {
left[i] = Math.max(left[i - 1], prices[i] - min);
min = Math.min(min, prices[i]);
}
int max = prices[len - 1];
int[] right = new int[len];
for (int i = len - 2; i >= 0; i--) {
right[i] = Math.max(right[i + 1], max - prices[i]);
max = Math.max(max, prices[i]);
}
int profit = 0;
for (int i = 0; i < len; i++) {
profit = Math.max(profit, left[i] + right[i]);
}
return profit;
}
\end{Code}
\newpage
\section{Best Time to Buy and Sell Stock IV} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
\textbf{Note:}
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
\subsubsection{Solution}
\begin{Code}
public int maxProfit(int k, int[] prices) {
int len = prices.length;
if (k >= len) {
int sum = 0;
for (int i = 1; i < len; i++) {
sum += Math.max(0, prices[i] - prices[i - 1]);
}
return sum;
}
int[][] local = new int[len][k + 1];
int[][] global = new int[len][k + 1];
for (int i = 1; i < len; i++) {
int diff = prices[i] - prices[i - 1];
for (int j = 1; j <= k; j++) {
local[i][j] = Math.max(global[i - 1][j - 1] + Math.max(0, diff), local[i - 1][j] + diff);
global[i][j] = Math.max(local[i][j], global[i - 1][j]);
}
}
return global[len - 1][k];
}
\end{Code}
\newpage
\section{Best Time to Buy and Sell Stock with Cooldown} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
\textbf{Example:}
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
\subsubsection{Solution}
\begin{Code}
public int maxProfit(int[] prices) {
int sell = 0, prev_sell = 0, buy = Integer.MIN_VALUE, prev_buy;
for (int price : prices) {
prev_buy = buy;
buy = Math.max(prev_sell - price, prev_buy);
prev_sell = sell;
sell = Math.max(prev_buy + price, prev_sell);
}
return sell;
}
\end{Code}
\newpage
\section{Maximum Subarray} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array \code{[-2,1,-3,4,-1,2,1,-5,4]},
the contiguous subarray \code{[4,-1,2,1]} has the largest sum = 6.
\textbf{More practice:}
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
\subsubsection{Solution I}
\begin{Code}
public int maxSubArray(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
dp[i] = nums[i];
if (i > 0 && dp[i - 1] > 0) {
dp[i] += dp[i - 1];
}
max = Math.max(max, dp[i]);
}
return max;
}
\end{Code}
\subsubsection{Solution II}
\begin{Code}
public int maxSubArray2(int[] nums) {
int max = Integer.MIN_VALUE, prev = 0;
for (int i = 0; i < nums.length; i++) {
prev = Math.max(nums[i], nums[i] + prev);
max = Math.max(max, prev);
}
return max;
}
\end{Code}
\newpage
\section{Word Break} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = \code{"leetcode"},
dict = \code{["leet", "code"]}.
Return true because \code{"leetcode"} can be segmented as \code{"leet code"}.
\subsubsection{Solution}
\begin{Code}
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (String word : wordDict) {
int j = i - word.length();
if (j >= 0 && dp[j] && s.substring(j, i).equals(word)) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
\end{Code}
\newpage
\section{Counting Bits} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
\textbf{Example:}
For num = 5 you should return [0,1,1,2,1,2].
\textbf{Follow up:}
1. It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
2. Space complexity should be O(n).
3. Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
\subsubsection{Solution}
\begin{Code}
\end{Code}
\newpage
\section{Maximum Product Subarray} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array \code{[2,3,-2,4]},
the contiguous subarray \code{[2,3]} has the largest product = 6.
\subsubsection{Solution}
\begin{Code}
/**
* 这题很容易错的地方在于要同时记住最大值和最小值,因为可能有负数,
* 最小的负数乘以负数可能会变成最大的正直
*/
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int result = Integer.MIN_VALUE, max = 1, min = 1;
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
max = min = nums[i];
} else {
/**
* 这里一定要先给之前的值记下来,不然在算min时用到的max已经是当前改过的了
*/
int prevMax = max, prevMin = min;
max = Math.max(nums[i], Math.max(nums[i] * prevMax, nums[i] * prevMin));
min = Math.min(nums[i], Math.min(nums[i] * prevMax, nums[i] * prevMin));
}
result = Math.max(result, max);
}
return result;
}
\end{Code}
\newpage
\section{Largest Rectangle in Histogram} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
\begin{center}
\includegraphics[width=150pt]{histogram.png}
\includegraphics[width=150pt]{histogram2.png}
\end{center}
\subsubsection{Analysis}
\begin{Code}
这题关键是对于每根柱子,往两边延伸到某根柱子比自己矮或到边界为止。
暴力办法是依次循环,时间复杂度O(n^2),空间复杂度O(n)
采用动态规划延伸的时候可以根据之前的结果跳着走,最优时间复杂度O(n),最差时间复杂度O(n^2),
平均时间复杂度O(n),空间复杂度O(n)
采用压栈的方法最巧妙,时间复杂度O(n),空间复杂度O(n)
\end{Code}
\newpage
\subsubsection{Solution I}
\begin{Code}
// 这种超时了,复杂度O(n^2)
public int largestRectangleArea(int[] heights) {
int max = 0;
for (int i = 0, j, k; i < heights.length; i++) {
for (j = i - 1; j >= 0 && heights[j] >= heights[i]; j--);
for (k = i + 1; k < heights.length && heights[k] >= heights[i]; k++);
max = Math.max(max, (k - j - 1) * heights[i]);
}
return max;
}
/** 注意栈中的是index,不是高度 */
public int largestRectangleArea2(int[] heights) {
int max = 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i <= heights.length; ) {
int height = i == heights.length ? 0 : heights[i];
if (stack.isEmpty() || height > heights[stack.peek()]) {
stack.push(i++);
} else {
int top = stack.pop();
int left = stack.isEmpty() ? 0 : stack.peek() + 1;
max = Math.max(max, heights[top] * (i - 1 - left + 1));
}
}
return max;
}
\end{Code}
\subsubsection{Solution II}
\begin{Code}
// 耗时4ms
public int largestRectangleArea3(int[] heights) {
int len = heights.length, j;
int[] left = new int[len], right = new int[len];
for (int i = 0; i < len; i++) {
for (j = i; j >= 1 && heights[j - 1] >= heights[i]; j = left[j - 1]);
left[i] = j;
}
for (int i = len - 1; i >= 0; i--) {
for (j = i; j < len - 1 && heights[j + 1] >= heights[i]; j = right[j + 1]);
right[i] = j;
}
int max = 0;
for (int i = 0; i < len; i++) {
max = Math.max(max, (right[i] - left[i] + 1) * heights[i]);
}
return max;
}
\end{Code}
\newpage
\section{Maximal Rectangle} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
\begin{Code}
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
\end{Code}
Return 6.
\subsubsection{Solution I}
\begin{Code}
// 耗时10ms,时间复杂度是O(mn),空间复杂度O(n)
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0) {
return 0;
}
int row = matrix.length, col = matrix[0].length, max = 0;
int[] heights = new int[col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] == '0') {
heights[j] = 0;
} else {
heights[j]++;
}
}
max = Math.max(max, largestRectangleArea(heights));
}
return max;
}
\end{Code}
\newpage
\subsubsection{Solution II}
\begin{Code}
// 耗时9ms
public int maximalRectangle2(char[][] matrix) {
if (matrix.length == 0) {
return 0;
}
int row = matrix.length, col = matrix[0].length, area = 0;
int[] height = new int[col], left = new int[col], right = new int[col];
for (int i = 0; i < col; right[i] = col - 1, i++);
for (int i = 0; i < row; i++) {
int leftStart = 0, rightStart = col - 1;
for (int j = 0; j < col; j++) {
if (matrix[i][j] == '0') {
height[j] = 0;
} else {
height[j]++;
}
}
// 注意当matrix[i][j]为0时其实left[j]和right[j]是多少已经不重要了,因为
// height[j]为0,所以这里算left[j]和right[j]只是为了方便计算下一层
// 所以left[j]=0好理解,而right[j]=col-1的目的是为了设置成最大的,因为下一层要求min
for (int j = 0; j < col; j++) {
if (matrix[i][j] == '0') {
left[j] = 0;
leftStart = j + 1;
} else {
left[j] = Math.max(left[j], leftStart);
}
}
for (int j = col - 1; j >= 0; j--) {
// 注意这里不是0,而是字符'0'
if (matrix[i][j] == '0') {
right[j] = col - 1;
rightStart = j - 1;
} else {
right[j] = Math.min(right[j], rightStart);
}
}
for (int j = 0; j < col; j++) {
area = Math.max(area, (right[j] - left[j] + 1) * height[j]);
}
}
return area;
}
\end{Code}
\newpage
\section{Maximal Square} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
For example, given the following matrix:
\begin{Code}
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
\end{Code}
Return 4.
\subsubsection{Solution}
\begin{Code}
/**
* 这题要返回的是面积
*/
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int row = matrix.length, col = matrix[0].length;
int[][] f = new int[row][col];
int max = 0;
for (int i = 0; i < col; i++) {
f[0][i] = matrix[0][i] == '1' ? 1 : 0;
max = Math.max(max, f[0][i]);
}
for (int i = 0; i < row; i++) {
f[i][0] = matrix[i][0] == '1' ? 1 : 0;
max = Math.max(max, f[i][0]);
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][j] == '0') {
f[i][j] = 0;
} else {
int mn = Math.min(f[i - 1][j], f[i][j - 1]);
f[i][j] = Math.min(mn, f[i - 1][j - 1]) + 1;
max = Math.max(max, f[i][j]);
}
}
}
return max * max;
}
\end{Code}
\newpage
\section{Edit Distance} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
\subsubsection{Solution}
\begin{Code}
public int minDistance(String word1, String word2) {
int len1 = word1.length(), len2 = word2.length();
int[][] f = new int[len1 + 1][len2 + 1];
for (int i = 1; i <= len1; i++) {
f[i][0] = i;
}
for (int i = 1; i <= len2; i++) {
f[0][i] = i;
}
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1];
} else {
int min = Math.min(f[i][j - 1], f[i - 1][j]);
f[i][j] = Math.min(f[i - 1][j - 1], min) + 1; /** 这里的加1别掉了 */
}
}
}
return f[len1][len2];
}
\end{Code}
\newpage
\section{One Edit Distance} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given two strings S and T, determine if they are both one edit distance apart.
\subsubsection{Solution}
\begin{Code}
/**
* 最容易错的是结尾的条件sL != tL
*/
public boolean isOneEditDistance(String s, String t) {
int sL = s.length(), tL = t.length();
if (sL > tL) {
return isOneEditDistance(t, s);
}
if (tL - sL > 1) {
return false;
}
for (int i = 0; i < sL; i++) {
if (s.charAt(i) != t.charAt(i)) {
if (sL < tL) {
return s.substring(i).equals(t.substring(i + 1));
} else {
return s.substring(i + 1).equals(t.substring(i + 1));
}
}
}
return sL != tL;
}
\end{Code}
\newpage
\section{Distinct Subsequences} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = \code{"rabbbit"}, T = \code{"rabbit"}
Return 3.
\subsubsection{Solution}
\begin{Code}
\end{Code}
\newpage
\section{Triangle} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
\begin{Code}
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
\end{Code}
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
\textbf{Note:}
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
\subsubsection{Solution}
\begin{Code}
\end{Code}
\newpage
\section{Perfect Squares} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
\subsubsection{Solution}
\begin{Code}
public int numSquares(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int min = Integer.MAX_VALUE;
for (int k = 1; i - k * k >= 0; k++) {
min = Math.min(min, 1 + dp[i - k * k]);
}
dp[i] = min;
}
return dp[n];
}
\end{Code}
\newpage
\section{Range Sum Query - Immutable} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
\textbf{Example:}
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
\textbf{Note:}
You may assume that the array does not change.
There are many calls to sumRange function.
\subsubsection{Solution}
\begin{Code}
private int[] sums;
public RangeSumQueryImmutable(int[] nums) {
sums = new int[nums.length];
for (int sum = 0, i = 0; i < nums.length; i++) {
sum += nums[i];
sums[i] = sum;
}
}
public int sumRange(int i, int j) {
int sum1 = i > 0 ? sums[i - 1] : 0;
return sums[j] - sum1;
}
\end{Code}
\newpage
\section{Range Sum Query 2D - Immutable} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
\begin{center}
\includegraphics[width=60pt]{range.png}
\end{center}
\textbf{Example:}
\begin{Code}
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8, sumRegion(1, 1, 2, 2) -> 11, sumRegion(1, 2, 2, 4) -> 12
\end{Code}
\textbf{Note:}
1. You may assume that the matrix does not change.
2. There are many calls to sumRegion function.
3. You may assume that row1 ≤ row2 and col1 ≤ col2.
\subsubsection{Solution}
\begin{Code}
public class NumMatrix {
private int[][] dp;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0) {
return;
}
int row = matrix.length;
int col = matrix[0].length;
dp = new int[row + 1][col + 1];
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return dp[row2 + 1][col2 + 1] - dp[row2 + 1][col1] - dp[row1][col2 + 1] + dp[row1][col1];
}
}
\end{Code}
\newpage
\section{Unique Paths} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
\begin{center}
\includegraphics[width=100pt]{robot.png}\\
\end{center}
\textbf{Note:} m and n will be at most 100.
\subsubsection{Solution}
\begin{Code}
\end{Code}
\newpage
\section{Unique Paths II} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
\begin{Code}
[
[0,0,0],
[0,1,0],
[0,0,0]
]
\end{Code}
The total number of unique paths is 2.
\textbf{Note:} m and n will be at most 100.
\subsubsection{Solution}
\begin{Code}
\end{Code}
\newpage
\section{Burst Balloons} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
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.
\textbf{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
\textbf{Example:}
Given [3, 1, 5, 8]
Return 167
\begin{Code}
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
\end{Code}
\subsubsection{Solution}
\begin{Code}
/**
* 这题用的闭区间DP,dp[start][end]表示区间start,end内所有气球爆掉的最大coin
* 假设最后爆第i个气球,start <= i <= end,则对应的coin为
* coin = nums[start - 1] * nums[i] * nums[end + 1] + dp[start, i - 1] + dp[i + 1][end]
* 为什么最后爆呢,因为这样以i为分隔线的左右两边就相互独立了,否则如果先爆i,则i的左右两个气球就相邻了
* 为什么最后爆i时,其相邻值取nums[start - 1]和nums[end + 1]呢?放在全局来看,
* 就是nums[-1]和nums[n]都为1
*/