-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathleetcode.cpp
More file actions
7194 lines (6883 loc) · 214 KB
/
leetcode.cpp
File metadata and controls
7194 lines (6883 loc) · 214 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
------------3Sum.cpp------------- -1
//跟2sum思路一样,2sum是线性复杂度,3sum是平方复杂度
//关于“一定要跳过重复元素”:例如, -2 -1 -1 0 1 2 中的-1,
//取过了第一个-1,则第二个-1完全没必要再取做第一个元素了
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
int len = num.size();
vector<int> v, v_last;
vector<vector<int> > v_res;
if(len<3) return v_res;
//为了后面用两头逼近法,先要排个序
sort(num.begin(), num.end());
for(int i=0; i<len-2; i++) {
int target = 0-num[i]; //计算target
int head = i+1, tail = len - 1;
//一定要跳过重复元素
if(i>0 && num[i] == num[i-1]){
continue;
}
//这里用了2sum的算法
while(head < tail){
v.clear();
//如果找到了一个结果
if(num[head]+num[tail] == target){
v.push_back(num[i]);
v.push_back(num[head++]);
v.push_back(num[tail--]);
//v_last记录上一个结果,因为有重复元素,所以需要判重
if(v_last != v){
v_res.push_back(v);
v_last = v;
}
}
else if(num[head]+num[tail] < target){
head++;
}
else if(num[head]+num[tail] > target){
tail--;
}
}
}
return v_res;
}
};
------------3Sum Closest.cpp------------0
//跟3sum没什么不一样
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int len = num.size();
int sum = 0, target_2sum, head, tail;
int diff, diff_min = (1<<31)-1;
if(len<=3){
for(int i=0; i<len; i++){
sum += num[i];
}
return sum;
}
//先排序
sort(num.begin(),num.end());
for(int i=0; i<len-2; i++){
target_2sum = target - num[i];
head = i+1;
tail = len-1;
//2sum左右逼近
while(head < tail){
sum = num[i]+num[head]+num[tail];
diff = target - sum;
if(diff == 0){
return target;
}
if(diff<0){
tail--;
}
else if(diff>0){
head++;
}
//更新最小差距
if(abs(diff_min)>abs(diff)){
diff_min = diff;
}
}
}
return target - diff_min;
}
};
--------------end--------------
------------3Sum.cpp------------1
//跟2sum思路一样,2sum是线性复杂度,3sum是平方复杂度
//关于“一定要跳过重复元素”:例如, -2 -1 -1 0 1 2 中的-1,
//取过了第一个-1,则第二个-1完全没必要再取做第一个元素了
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
int len = num.size();
vector<int> v, v_last;
vector<vector<int> > v_res;
if(len<3) return v_res;
//为了后面用两头逼近法,先要排个序
sort(num.begin(), num.end());
for(int i=0; i<len-2; i++) {
int target = 0-num[i]; //计算target
int head = i+1, tail = len - 1;
//一定要跳过重复元素
if(i>0 && num[i] == num[i-1]){
continue;
}
//这里用了2sum的算法
while(head < tail){
v.clear();
//如果找到了一个结果
if(num[head]+num[tail] == target){
v.push_back(num[i]);
v.push_back(num[head++]);
v.push_back(num[tail--]);
//v_last记录上一个结果,因为有重复元素,所以需要判重
if(v_last != v){
v_res.push_back(v);
v_last = v;
}
}
else if(num[head]+num[tail] < target){
head++;
}
else if(num[head]+num[tail] > target){
tail--;
}
}
}
return v_res;
}
};
--------------end--------------
------------4Sum.cpp------------2
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int len = num.size(), target2;
vector<vector<int> > v_res;
vector<int> v;
if(len < 4) return v_res; //如果len小于4,则返回空vector
sort(num.begin(), num.end()); //对数组排序
//枚举的时候,位置不发生变化
for(int i=0; i<len-3; i++){
for(int j=i+1; j<len-2; j++){
target2 = target - (num[i]+num[j]);
int head = j+1, tail = len-1;
while(head < tail){
if(num[head]+num[tail] < target2){
head++;
}
else if(num[head]+num[tail] > target2){
tail--;
}
else{
v.push_back(num[i]);
v.push_back(num[j]);
v.push_back(num[head]);
v.push_back(num[tail]);
v_res.push_back(v);
v.clear();
head++;
tail--;
}
}
}
}
set<vector<int> > s(v_res.begin(), v_res.end());
v_res.assign(s.begin(), s.end());
return v_res;
}
};
--------------end--------------
------------Add Binary.cpp------------3
//很简单,就是模拟相加,开始的时候先知道那个串更长,这样好做点
class Solution {
public:
string addBinary(string a, string b) {
int len_a = a.length(), temp;
int len_b = b.length();
int carry = 0;
string c = "";
if(len_a < len_b) {
return addBinary(b, a);
}
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
for(int i = 0; i < len_a; i++){
if(i < len_b)
temp = (a[i]-'0')+(b[i]-'0')+carry;
else
temp = (a[i]-'0')+carry;
if(temp >= 2) carry = 1;
else carry = 0;
temp %= 2;
c += (temp+'0');
}
if(carry){
c += (carry+'0');
}
reverse(c.begin(), c.end());
return c;
}
};
//另一种写法
class Solution {
public:
string addBinary(string a, string b) {
string result;
const size_t n = a.size() > b.size() ? a.size() : b.size();
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int carry = 0;
for (size_t i = 0; i < n; i++) {
const int ai = i < a.size() ? a[i] - '0' : 0;
const int bi = i < b.size() ? b[i] - '0' : 0;
const int val = (ai + bi + carry) % 2;
carry = (ai + bi + carry) / 2;
result.insert(result.begin(), val + '0');
}
if (carry == 1) {
result.insert(result.begin(), '1');
}
return result;
}
};
--------------end--------------
------------Add Two Numbers.cpp------------4
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
思路:考察基本的链表操作,一种不太好的做法是另外分配一个空间放结果,
我决定不使用额外空间, 所以第一次写了70多行代码才AC,
后来经过改进,就变成了下面的40多行代码
*/
class Solution {
public:
int add(int a, int b, int *carry){
int res = a+b+*carry;
if(res >= 10){
*carry = 1;
return res%10;
}
else{
*carry = 0;
return res;
}
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int carry = 0;
ListNode *ll1 = l1, *ll2 = l2, *last;
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
while(l1 && l2){
l2->val = l1->val = add(l1->val, l2->val, &carry);
last = l1;
l1 = l1->next;
l2 = l2->next;
}
ListNode *remain = l2?l2:l1, *res = l2?ll2:ll1;
while(remain){
remain->val = add(remain->val, 0, &carry);
last = remain;
remain = remain->next;
}
if(carry){
last->next = new ListNode(1);
}
return res;
}
};
--------------end--------------
------------Anagrams.cpp------------5
//貌似如果有重复的词也一律认为是anagram,
//而且,只要是anagram一律存到vector里不用担心顺序问题
//思路:对单词排序,然后存入map,如果map中有,则连同
//原有的词一起push到vector
//技巧:如果map中原来没有,则value存的是第一个出现的词的index
//这是为了找到第二个的时候,连同上一个一起存到vector,
//如果已经有了,就存-1,表明之前已经有了
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
int size = strs.size();
vector<string> res;
map<string, int> mp_anagram;
for(int i=0; i<size; i++){
string tmp = strs[i];
sort(tmp.begin(), tmp.end());
map<string, int>::iterator it = mp_anagram.find(tmp);
if(it == mp_anagram.end()){
mp_anagram[tmp] = i;
}
else {
if(mp_anagram[tmp] == -1) {
res.push_back(strs[i]);
}
else {
//mp_anagram[tmp]存的是第一个词的index
res.push_back(strs[mp_anagram[tmp]]);
mp_anagram[tmp] = -1;
res.push_back(strs[i]);
}
}
}
return res;
}
};
--------------end--------------
------------Balanced Binary Tree.cpp------------6
First Try:
//递归计算两边的深度,深度差不大于1才算平衡
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode *root){
if(root == NULL)
return 0;
else{
int l, r;
l = getDepth(root->left);
r = getDepth(root->right);
return max(l,r)+1;
}
}
bool isBalanced(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == NULL)
return true;
int diff = getDepth(root->left) - getDepth(root->right);
if(diff > 1 || diff < -1)
return false;
if(!isBalanced(root->left) || !isBalanced(root->right))
return false;
return true;
}
};
--------------end--------------
------------Best Time to Buy and Sell Stock II.cpp------------7
First Try:
/*
* find all accending sub-sequence in the vector and get all the profit in each sub-sequence
* sum them up 所有上升子序列相加
*/
class Solution {
public :
int maxProfit( vector< int> & prices) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector< int> accending;
int profit = 0;
if( prices.size()){
accending.push_back( prices[0]); // if prices not null, push first price to vector
}
for( int i=0; i<( int) prices.size()-1; i++){
if( prices[i] > prices[i+1]){ // if the price descend
profit += accending.back()-accending.front();
accending.clear(); // clear the vector to save next accending vector
accending.push_back( prices[i+1]); // push the first price in next sequence
}
else { // if the price accend
accending.push_back( prices[i+1]); // continue to push into vector
}
}
if(accending.size()){
profit += accending.back()-accending.front(); // for the last accending vector
}
return profit;
}
};
Second Try:
//先把原始价格序列变成差分序列,贪心法,低进高出,把所有正的价格差价相加起来。
class Solution {
public :
int maxProfit( vector< int> & prices) {
int sum = 0;
for(int i=1; i<prices.size(); i++) {
int diff = prices[i] - prices[i-1];
if(diff > 0) sum += diff;
}
return sum;
}
}
--------------end--------------
------------Best Time to Buy and Sell Stock III.cpp------------8
/*
思路:O(n平方)的方法,对每个点进行分割,算出这个点两边的最大利润相加
O(n)的方法,先正向算出从起点开始到每个点的最大利润,再逆向算出从每个点开始到终点的最大利润
进而就得出了最大利润,以第i点进行分割,i点不可能同时为前段的终点和后段的起点,所以不用担心
*/
class Solution {
public:
int maxProfit(vector<int> &prices)
{
vector<int> profit(prices.size());
int min_price = INT_MAX;
//先得到从左到右的最大利润(起点固定)
for (int i = 0; i < prices.size(); i++) {
if (prices[i] < min_price) min_price = prices[i]; //更新左起最小price
profit[i] = max(profit[i], prices[i]-min_price); //更新最大利润
}
//再得到从右到左的最大利润(终点固定)
int max_price = INT_MIN , max_profit = 0, res = 0;
for (int i = prices.size() - 1; i >= 0 ; i--) {
if (prices[i] > max_price) max_price = prices[i]; //更新右起最大price
else max_profit = max(max_profit, max_price - prices[i]); //更新最大利润
res = max(profit[i]+ max_profit, res);
}
return res;
}
};
--------------end--------------
------------Best Time to Buy and Sell Stock.cpp------------9
/*
扫描一遍,记录下遇到的min price,拿当前price减去min price,
记录下最大的profit
*/
class Solution {
public :
int maxProfit(vector< int> &prices) {
int min_price, profit = 0, len = prices.size();
if(len) min_price = prices[0]; //初始化最小价格
for(int i=1; i<len; i++){
//更新最小价格
min_price = min(prices[i], min_price);
//用当前最小价格计算最大利润
profit = prices[i]-min_price > profit? prices[i]-min_price : profit;
}
return profit;
}
};
--------------end--------------
------------Binary Tree Inorder Traversal.cpp------------10
First Try:
递归,只使用一个函数
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> v;
if(root == NULL){
return v;
}
if(root->left){
vector<int> v_t;
v_t = inorderTraversal(root->left);
v.insert(v.end(), v_t.begin(), v_t.end());
}
v.push_back(root->val);
if(root->right){
vector<int> v_t;
v_t = inorderTraversal(root->right);
v.insert(v.end(), v_t.begin(), v_t.end());
}
return v;
}
};
Second Try:
递归, 两个函数
class Solution {
public:
void inorderTraversal(TreeNode *root, vector<int> &v) {
if(root->left) inorderTraversal(root->left, v);
v.push_back(root->val);
if(root->right) inorderTraversal(root->right, v);
}
vector<int> inorderTraversal(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> v;
if(root == NULL){
return v;
}
inorderTraversal(root, v);
return v;
}
};
Thrid Try:
非递归,栈
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode *> s;
vector<int> v;
TreeNode *p = root;
while(p != nullptr || !s.empty()) {
if(p != nullptr) {
s.push(p);
p = p->left;
}
else {
p = s.top(); s.pop();
v.push_back(p->val);
p = p->right;
}
}
return v;
}
};
--------------end--------------
------------Binary Tree Level Order Traversal II.cpp------------11
First Try:
//用vector模拟队列操作,太傻了
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > v_res;
vector<int> v;
vector<TreeNode*> tree;
int head = 0, tail = 0;
if(root){
tree.push_back(root);
tail++;
}
while(head!=tail){
int tail_current = tail;
for(; head<tail_current; head++){
v.push_back(tree[head]->val);
if(tree[head]->left){
tree.push_back(tree[head]->left);
tail++;
}
if(tree[head]->right){
tree.push_back(tree[head]->right);
tail++;
}
}
v_res.push_back(v);
v.clear();
}
reverse(v_res.begin(), v_res.end());
return v_res;
}
};
Second Try:
//用队列实现, 很清楚的过程, 无需多言
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int>> v_res;
vector<int> v;
queue<TreeNode *> q;
if(root != nullptr) q.push(root);
while(!q.empty()){
int size = q.size();
for(int i = 0; i < size; i++) {
TreeNode *t = q.front(); q.pop(); //得到队列头
v.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
v_res.push_back(v);
v.clear();
}
reverse(v_res.begin(), v_res.end());
return v_res;
}
};
--------------end--------------
------------Binary Tree Maximum Path Sum.cpp------------12
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
int res = INT_MIN;
maxPathSumRe(root, res);
return res;
}
int maxPathSumRe(TreeNode *node, int &res)
{
if (!node) return 0;
int l = maxPathSumRe(node->left, res); //返回左边单线最大值
int r = maxPathSumRe(node->right, res); //返回右边单线最大值
int sum = max(node->val, max(l, r) + node->val); //以当前节点为终点的最大可能值(单线)
//更新最大和
res = max(res, sum); //用单线最大值试试
res = max(res, l + r + node->val); //用双线最大值试试
return sum;
}
};
/*可以利用“最大连续子序列和”问题的思路,见Maximum Subarray。如果说Array 只有一个方向的话,
那么Binary Tree 其实只是左、右两个方向而已,我们需要比较两个方向上的值。
不过,Array 可以从头到尾遍历,那么Binary Tree 怎么办呢,我们可以采用Binary Tree 最常用
的dfs 来进行遍历。先算出左右子树的结果L 和R,如果L 大于0,那么对后续结果是有利的,我们
加上L,如果R 大于0,对后续结果也是有利的,继续加上R。*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
max_sum = INT_MIN;
dfs(root);
return max_sum;
}
private:
int max_sum;
int dfs(const TreeNode *root) {
if (root == nullptr) return 0;
//计算左右子树的最大值
int l = dfs(root->left);
int r = dfs(root->right);
int sum = root->val;
//左右子树的贡献
if (l > 0) sum += l;
if (r > 0) sum += r;
//更新最大和
max_sum = max(max_sum, sum);
//返回当前树中单一路径能得到的最大值
return max(r, l) > 0 ? max(r, l) + root->val : root->val;
}
};
--------------end--------------
------------Binary Tree Postorder Traversal.cpp------------13
My solution:
我居然用list双向链表代替stack,很不专业啊
过程是如果左右子树非空就压栈(先右再左,因为要先访问左)
出栈有两个条件:1、栈顶节点的左右都是空节点 2、刚访问了栈顶节点的子节点
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> ans;
TreeNode *last = root, *cur;
list<TreeNode*> node_list;
if(root == NULL) return ans;
node_list.push_front(root);
while(!node_list.empty())
{
cur= node_list.front();
if(cur -> right == last || cur -> left == last || //刚才访问的是子节点
((cur -> right == NULL) && (cur -> left == NULL))) //没有子节点了就pop
{
node_list.pop_front();
ans.push_back(cur -> val);
last = cur;
}
else {
if(cur -> right != NULL) node_list.push_front(cur -> right);//right son first
if(cur -> left != NULL) node_list.push_front(cur -> left); //left son second
}
}
}
};
更专业的solution:
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
/* p,正在访问的结点,q,刚刚访问过的结点*/
const TreeNode *p, *q;
stack<const TreeNode *> s;
p = root;
do {
while (p != nullptr) { /* 往左下走*/
s.push(p);
p = p->left;
}
q = nullptr;
while (!s.empty()) {
p = s.top();
s.pop();
/* 右孩子不存在或已被访问,访问之*/
if (p->right == q) {
result.push_back(p->val);
q = p; /* 保存刚访问过的结点*/
}
else {
/* 当前结点不能访问,需第二次进栈*/
s.push(p);
/* 先处理右子树*/
p = p->right;
break;
}
}
} while (!s.empty());
return result;
}
};
我觉得上面这个方法还没我的好,因为while里面套2个while,太绕了
我还是用stack来改写下第一段代码吧
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ans;
const TreeNode *last = root, *cur;
stack<const TreeNode *> node_list;
if(root == NULL) return ans;
node_list.push(root);
while(!node_list.empty())
{
cur= node_list.top();
if(cur -> right == last || cur -> left == last || //刚才访问的是子节点
((cur -> right == NULL) && (cur -> left == NULL))) //没有子节点了就pop
{
node_list.pop();
ans.push_back(cur -> val);
last = cur;
}
else {
if(cur -> right != NULL) node_list.push(cur -> right);//right son first
if(cur -> left != NULL) node_list.push(cur -> left); //left son second
}
}
}
};
--------------end--------------
------------Binary Tree Preorder Traversal.cpp------------14
First Try: 非递归,用栈实现
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//先序遍历只需要一个栈
//先访问当前节点,然后把当前节点入栈
//接着访问左节点并入栈直到再无左节点
//出栈开始对右节点的访问,这个流程要烂熟于心
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode *> s;
vector<int> v;
TreeNode *p = root;
while(p != nullptr || !s.empty()){
if(p != nullptr){
v.push_back(p->val);
s.push(p);
p = p->left;
}
else{
p = s.top();
s.pop();
p = p->right;
}
}
return v;
}
};
Second Try:
class Solution {
public:
void preorderTraversal(TreeNode *root, vector<int> &v) {
v.push_back(root->val);
if(root->left != nullptr) preorderTraversal(root->left, v);
if(root->right != nullptr) preorderTraversal(root->right, v);
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> v;
v.clear();
if(root == nullptr) return v;
preorderTraversal(root, v);
return v;
}
};
Third Try:
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
const TreeNode *p;
stack<const TreeNode *> s;
p = root;
if (p != nullptr) s.push(p);
while (!s.empty()) {
p = s.top();
s.pop();
result.push_back(p->val);
if (p->right != nullptr) s.push(p->right);
if (p->left != nullptr) s.push(p->left);
}
return result;
}
};
--------------end--------------
------------Binary Tree Zigzag Level Order Traversal.cpp------------15
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
其实就是按层访问的变形,用一个队列,用一个变量记录行号,
对奇数行逆序,对偶数行保留原来的顺序不变
*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > ret;
queue<TreeNode *> TreeQueue;
TreeNode *temp;
TreeQueue.push(root);
int size;
if(!root) return ret;
while(size = TreeQueue.size()) { //得到当前队列的size
vector<int> v;
//把当前队列全部出列,并放到ret中,同时push下一层的节点
for(int i=0; i<size; i++){
temp = TreeQueue.front();
TreeQueue.pop();
v.push_back(temp->val);
if(temp->left) TreeQueue.push(temp->left);
if(temp->right) TreeQueue.push(temp->right);
}
ret.push_back(v);
}
for(int i=0; i<ret.size(); i++){
if(i%2){ //奇数行逆序
reverse(ret[i].begin(), ret[i].end());
}
}
return ret;
}
};
--------------end--------------
------------Candy.cpp------------16
/*
从不同方向扫描两遍即可
*/
class Solution {
public:
int candy(vector<int> &ratings) {
int size = ratings.size();
//给每个人一个糖
vector<int> candy(size, 1);
//先从左向右扫描
for(int i=1; i<size; i++){
if(ratings[i] > ratings[i-1]){
candy[i] = candy[i-1] + 1;
}
}
int res = candy[size-1];
//再从右向左扫描
for(int i=size-2; i>=0; i--){
if(ratings[i] > ratings[i+1] && candy[i] <= candy[i+1]){
candy[i] = candy[i+1] + 1;
}
res += candy[i];
}
return res;
}
};
--------------end--------------
------------Climbing Stairs.cpp------------17
First Try:
//最简单的动态规划
class Solution {
public:
int climbStairs(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int *k = new int[n+1];
k[1] = 1; k[2] = 2;
for(int i=3; i<=n; i++){
k[i] = k[i-1] + k[i-2];
}
return k[n];
}
};
Second Try:
//O(1)的空间复杂度
class Solution {
public:
int climbStairs(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int a = 1, b = 2, c;
if(n==1) return a;
if(n==2) return b;
for(int i=3; i<=n; i++){
c = a+b;
a = b;
b = c;
}
return c;
}
};
--------------end--------------
------------Clone Graph.cpp------------18
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
/*
这里只能克隆连通图(当然)
方法:从一个点开始克隆,然后开始neighbor的克隆,用一个map记录visited,避免重复访问
*/
class Solution {
private:
map<UndirectedGraphNode *, UndirectedGraphNode *> visited;
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL){
return NULL;
}
if(visited[node]){
return visited[node];
}
UndirectedGraphNode *first_node = new UndirectedGraphNode(node->label);
visited[node] = first_node;
for(int i=0; i<node->neighbors.size(); i++){
first_node->neighbors.push_back(cloneGraph(node->neighbors[i]));