File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -601,7 +601,48 @@ func trap(height []int) int {
601
601
}
602
602
```
603
603
604
+ 动态规划解法:
605
+
606
+ ``` go
607
+ func trap (height []int ) int {
608
+ sum := 0
609
+ n := len (height)
610
+ lh := make ([]int ,n)
611
+ rh := make ([]int ,n)
612
+ lh[0 ]=height[0 ]
613
+ rh[n-1 ]=height[n-1 ]
614
+ for i := 1 ;i<n;i++{
615
+ lh[i]=max (lh[i-1 ],height[i])
616
+ }
617
+ for i := n-2 ;i>=0 ;i--{
618
+ rh[i]=max (rh[i+1 ],height[i])
619
+ }
620
+ for i := 1 ;i<n-1 ;i++{
621
+ h := min (rh[i],lh[i])-height[i]
622
+ if h>0 {
623
+ sum+=h
624
+ }
625
+ }
626
+ return sum
627
+ }
628
+ func max (a ,b int )int {
629
+ if a>b{
630
+ return a
631
+ }
632
+ return b
633
+ }
634
+ func min (a ,b int )int {
635
+ if a<b{
636
+ return a
637
+ }
638
+ return b
639
+ }
640
+ ```
641
+
642
+
643
+
604
644
JavaScript:
645
+
605
646
``` javascript
606
647
// 双指针
607
648
var trap = function (height ) {
You can’t perform that action at this time.
0 commit comments