-
Notifications
You must be signed in to change notification settings - Fork 2
/
080.cpp
20872 lines (16593 loc) · 425 KB
/
080.cpp
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
Table
373. Find K Pairs with Smallest Sums (M)
374. Guess Number Higher or Lower (M)
375. Guess Number Higher or Lower II (M)
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <functional>
#include <array>
#include <map>
#include <stack>
using namespace std;
//<--> Additional : Heap Sort
class CreateHeap
{
public:
static void heapify(vector<int>& A, int N, int root)
{
auto new_root = root;
auto l = new_root * 2 + 1;
auto r = l + 1;
if (l<N && A[l]>A[new_root])
{
new_root = l;
}
if (r<N && A[r]>A[new_root])
{
new_root = r;
}
if (new_root != root)
{
swap(A[new_root], A[root]);
heapify(A, N, new_root);
}
}
static void heap_sort(vector<int>& A)
{
int N = A.size();
for (int i = N / 2 - 1; i >= 0; --i)
{
heapify(A, N, i);
}
for (int i = N - 1; i >= 0; --i)
{
swap(A[i], A[0]);
heapify(A, i, 0);
}
}
};
//<--> 10. Regular Expression Matching
/*
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
*/
class Solution {
public:
bool isMatch(string s, string p)
{
vector<vector<int>> dp(s.size() + 1, vector<int>(p.size() + 1, 0));
dp[0][0] = 1;
for (size_t i = 2; i <= p.size(); ++i)
{
if (p[i - 1] == '*')
{
dp[0][i] = dp[0][i - 2];
}
}
for (size_t i = 1; i <= s.size(); ++i)
{
for (size_t j = 1; j <= p.size(); ++j)
{
if ( ( s[i - 1] == p[j - 1] ) || ( p[j - 1] = '.') )
{
dp[i][j] = dp[i - 1][j - 1];
}
else if (p[j - 1] == '*')
{
dp[i][j] = dp[i][j - 2]; // * match zero
if ((s[i - 1] = p[j - 2]) || p[j - 2] == '.')
{
dp[i][j] |= dp[i - 1][j]; //* match at least 1
}
}
}
}
return dp.back().back() == 1;
}
};
//<--> 21. Merge k Sorted Lists
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp {
bool operator () (ListNode *a, ListNode *b)
{
return a->val > b->val;
}
};
//using min heap;
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
for (int i = 0; i < lists.size(); ++i)
{
if (lists[i]) q.push(lists[i]);
}
ListNode *head = NULL, *pre = NULL, *tmp = NULL;
while (!q.empty())
{
tmp = q.top();
q.pop();
if (!pre)
{
head = tmp;
}
else
{
pre->next = tmp;
}
pre = tmp;
if (tmp->next)
{
q.push(tmp->next);
}
}
return head;
}
};
//28. Implement strStr()
/*
Implement strStr().
Returns the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
*/
class Solution {
public:
int strStr(string haystack, string needle)
{
if(needle.empty()||haystack.empty()) return -1;
auto m = haystack.size();
auto n = needle.size();
if( m< n )
{
return -1;
}
for( size_t i = 0; i<=m-n; ++i )
{
size_t j = 0;
for( j = 0; j<n; ++j )
{
if( haystack[i+j] != needle[j] )
{
break;
}
}
if(j==n) return i;
}
return -1;
}
};
//38. Count and Say
/*
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
*/
class Solution {
public:
string countAndSay(int n)
{
string res = "1";
for(int i = 1; i<n; ++i)
{
string tmp;
res.push_back('$');
int count = 1;
for(size_t j = 1; j < res.size(); ++j )
{
if(res[j-1]==res[j])
{
++count;
}
else
{
tmp.push_back(count+'0');
tmp.push_back(res[j-1]);
count = 1;
}
}
res = tmp;
}
return res;
}
};
//39. Combination Sum
/*
Given a set of candidate numbers (C) (without duplicates) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
*/
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
}
void dfs( vector<int>& nums, vector<int>& out, vector<vector<int>> &res, int target, int start )
{
if(target < 0)
{
return;
}
if(target == 0)
{
res.push_back(out);
return;
}
for(int i = start; i<nums.size();++i)
{
out.push_back(nums[i]);
dfs(nums,out,res,target-nums[i], i); //start is set to i not i+1 because "The same repeated number may be chosen"
out.pop_back();
}
}
};
//40. Combination Sum II
/*
Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
*/
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
{
vector<int> out;
vector<vector<int>> res;
sort(begin(candidates), end(candidates)); // key: must sort first.
dfs(candidates, 0, target, out, res);
return res;
}
void dfs(vector<int>& N, size_t start, int target, vector<int>& out, vector<vector<int>>& res)
{
if (target < 0)
{
return;
}
if (target == 0)
{
res.push_back(out);
return;
}
for (size_t i = start; i < N.size(); ++i)
{
if (i > start && N[i] == N[i - 1])
{
continue; //key: we need to sort first then we can use this feature to skip duplicate number
}
out.push_back(N[i]);
dfs(N, i + 1, target - N[i], out, res);
out.pop_back();
}
}
};
//41. First Missing Positive
/*
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
*/
class Solution {
public:
int firstMissingPositive(vector<int>& nums)
{
size_t i = 0;
auto n = nums.size();
while( i < n )
{
if(nums[i]!=i+1&&nums[i]>0&&nums[i]<=n&&nums[i]!=nums[nums[i]-1])
{
swap(nums[i],nums[nums[i]-1]);
}
else
{
++i;
}
}
for( i = 0; i<n;++i)
{
if(nums[i]!=i+1) return i+1;
}
return n+1;
}
};
//<--> 42. Trapping rain water
//Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
//Given [0,1,0,2,1,0, 1, 3, 2, 1, 2, 1], return 6
class Solution {
public:
int trap(vector<int>& height)
{
auto n = height.size();
vector<int> dp(n, 0);
int max_so_far = 0;
for( size_t i = 0; i < n; ++i )
{
dp[i] = max_so_far;
max_so_far = max(max_so_far, height[i]);
}
max_so_far = 0;
int res = 0;
for( size_t i = 0; i<n; ++i )
{
auto idx = n-1-i;
dp[idx] = min(max_so_far, dp[idx]);
max_so_far = max(max_so_far, height[idx]);
if(dp[idx] > height[idx])
{
res += (dp[idx]-height[idx]);
}
}
return res;
}
//second solution
int trap( vector<int>& height )
{
size_t l = 0, r = height.size() - 1;
int res = 0;
while (l < r)
{
auto min_h = min(height[l], height[r]);
if (height[l] == min_h)
{
++l;
while (l < r && height[l] < min_h)
{
res += min_h - height[l];
++l;
}
}
else
{
--r;
while (l < r && height[r] < min_h)
{
res += min_h - height[r];
--r;
}
}
}
}
};
//<--> 43. Multiply Strings
/*
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is less than 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
*/
class Solution {
public:
string multiply(string num1, string num2)
{
auto n1 = num1.size();
auto n2 = num2.size();
auto k = n1+n2-2;
vector<int> v(n1+n2,0);
for( size_t i = 0; i< n1; ++i )
{
for( size_t j = 0; j<n2; ++j)
{
v[k-i-j] += (num1[i]-'0')*(num2[i]-'0');
}
}
int carry = 0;
for(size_t i = 0; i<n1+n2; ++i)
{
v[i] += carry;
carry = v[i]/10;
v[i] -= carry * 10;
}
int i = n1+n2-1;
while(v[i]==0) --i;
if(i<0) return "0";
string res;
while(i>=0)
{
res.push_back(v[i]+'0');
--i;
}
return res;
}
//using std library
string multiply(string num1, string num2)
{
int len1 = num1.size();
int len2 = num2.size();
auto& s1 = num1;
auto& s2 = num2;
vector<int> v(len1 + len2, 0);
auto k = len1 + len2 - 2;
for (int i = 0; i < len1; ++i)
{
for (int j = 0; j < len2; ++j)
{
v[k - i - j] += (s1[i] - '0')*(s2[j] - '0');
}
}
int carry = 0;
for (size_t i = 0; i < v.size(); ++i)
{
v[i] += carry;
carry = v[i] / 10;
v[i] -= carry * 10;
}
auto it = find_if(v.rbegin(), v.rend(), [](int n) {return n != 0; });
if (it == v.rend())
{
return "0";
}
string res;
while (it != v.rend())
{
res.push_back(*it + '0');
++it;
}
return res;
}
};
//44. Wildcard Matching
/*
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
*/
/*
difference between regular matching and wildcard matching
1. in wildcard matching, '*' is a standalong pattern character
2. in regular maching, '*' is dependent on its previous character.
*/
class Solution {
public:
bool isMatch(string s, string p)
{
vector<vector<int>> dp(s.size() + 1, vector<int>(p.size() + 1));// key: add empty string
dp[0][0] = 1; //s is empty and p is empty, so they matched
//fill first row: s is empty and p is not empty
//so s="", and if p="***", they still can be matched
for (size_t i = 1; i <= p.size(); ++i)
{
if (p[i - 1] == '*')
{
dp[i - 1] = dp[i];
}
}
for (size_t i = 1; i <= s.size(); ++i)
{
for (size_t j = 1; j <= p.size(); ++j)
{
if (p[j - 1] == '*')
{
dp[i][j] = dp[i][j - 1] | dp[i - 1][j]; //dp[i][j-1] means '*' match zero character while dp[i-1][j] means '*' match s[i-1]
}
else if ((s[i - 1] == p[j - 1]) || (p[j - 1] == '?'))
{
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[s.size()][p.size()] == 1;
}
};
//45. Jump Game II
/*
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
*/
class Solution {
public:
int jump(vector<int>& nums)
{
auto n = nums.size();
size_t cur = 0;
size_t i = 0;
int res = 0;
while( cur < n-1 )
{
size_t pre = cur;
while( i <= pre )
{
cur = max(cur, i + nums[i]);
++i;
}
++res;
if(pre==cur) return -1;
}
return res;
}
};
//46. Permutations
/*
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
*/
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums)
{
vector<vector<int>> res;
dfs(nums, res, 0);
return res;
}
void dfs( vector<int>& nums, vector<vector<int>>& res, size_t start )
{
if( start==nums.size() )
{
res.push_back(nums);
}
else
{
for( size_t i = start; i< nums.size(); ++i )
{
swap(nums[start],nums[i]);
dfs(nums, res, start+1);
swap(nums[start],nums[i]);
}
}
}
};
//47. Permutations II
/*
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
*/
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums)
{
sort(begin(nums), end(nums));
vector<int> visit(nums.size(), 0);
vector<int> out;
vector<vector<int>> res;
dfs(nums, 0, out, visit, res);
return res;
}
void dfs(const vector<int>& N, size_t level, vector<int>& out, vector<int>& visit, vector<vector<int>>& res)
{
if (level == N.size())
{
res.push_back(out);
return;
}
for (size_t i = 0; i < N.size(); ++i)
{
if (visit[i] == 0)
{
if (i > 0 && N[i] == N[i - 1] && visit[i] == 1)
{
continue;
}
visit[i] = 1;
out.push_back(N[i]);
dfs(N, level + 1, out, visit, res);
out.pop_back();
visit[i] = 0;
}
}
}
};
//48. Rotate Image
/*
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
*/
class Solution {
public:
void rotate(vector<vector<int>>& matrix)
{
auto n = matrix.size();
for( size_t i = 0; i<n; ++i )
{
for( size_t j = i+1; j<n; ++j )
{
swap(matrix[i][j], matrix[j][i]);
}
reverse(matrix[i].begin(), matrix[i].end());
}
}
};
//49. Group Anagrams
/*
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs)
{
}
};
//50. Pow(x, n)
class Solution {
public:
double myPow(double x, int n)
{
double res = 1.0;
for(int i = n; i!=0; i/=2 )
{
if( i&1 != 0 ) res *= x;
x* = x;
}
}
//recursion
double myPow(double x, int n)
{
if( n<0 ) return 1.0 / Pow( x, -n );
return Pow(x,n);
}
double Pow(double x, int n)
{
if(n==0) return 1;
auto half = Pow(x, n/2);
if (n & 1 == 0) return half*half;
else return half*half*x;
}
};
//////////////////////////////////
// DP Initialization:
// // both text and pattern are null
// T[0][0] = true;
// // pattern is null
// T[i][0] = false;
// // text is null
// T[0][j] = T[0][j - 1] if pattern[j – 1] is '*'
// // If current characters match, result is same as
// // result for lengths minus one. Characters match
// // in two cases:
// // a) If pattern character is '?' then it matches
// // with any character of text.
// // b) If current characters in both match
// if ( pattern[j – 1] == ‘?’) ||
// (pattern[j – 1] == text[i - 1])
// T[i][j] = T[i-1][j-1]
// If we encounter ‘*’, two choices are possible-
// a) We ignore ‘*’ character and move to next
// character in the pattern, i.e., ‘*’
// indicates an empty sequence.
// b) '*' character matches with ith character in
// input
// else if (pattern[j – 1] == ‘*’)
// T[i][j] = T[i][j-1] || T[i-1][j]
// else // if (pattern[j – 1] != text[i - 1])
// T[i][j] = false
//53. Maximum Subarray
/*
Find the contiguous subarray within an array
(containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
*/
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
int res = nums[0];
int tmp = res;
for(size_t i = 1 ;i<nums.size(); ++i)
{
tmp = max(nums[i]+tmp, nums[i]);
res = max(tmp, res);
}
return res;
}
//using divide and conquer
int getMaxSubArray(vector<int>& nums, int left, int right)
{
if(left>=right) return nums[left];
int mid = left+(right-left)/2;
int lmax = getMaxSubArray(nums, left, mid-1);
int rmax = getMaxSubArray(nums, mid+1, right);
int cur_max = nums[mid], tmp = nums[mid];
for(int i = mid-1; i>=left; --i)
{
tmp += nums[i];
cur_max = max(tmp, cur_max);
}
tmp = cur_max;
for(int i = mid+1; i<=right; ++i)
{
tmp += nums[i];
cur_max = max(tmp, cur_max);
}
return max(cur_max, max(lmax, rmax));
}
};
//54. Spiral Matrix
/*
Given a matrix of m x n elements (m rows, n columns),
return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> res;