1717 * @return {number }
1818 */
1919
20- /** 1) Dynamic Programming */
20+ /** 1) Dynamic Programming (Recursion) */
2121// http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/
2222//
2323// Time O(n^3)
2828// Two people starting from (n-1, n-1) and go to (0, 0).
2929// They move one step (left or up) at a time simultaneously. And pick up the cherry within the grid (if there is one).
3030// If they ended up at the same grid with a cherry. Only one of them can pick up it.
31- const cherryPickup = ( grid ) => {
31+ const cherryPickup1 = ( grid ) => {
3232 if ( grid == null || grid . length === 0 ) return 0 ;
3333
3434 const n = grid . length ;
@@ -41,7 +41,7 @@ const cherryPickup = (grid) => {
4141
4242 const go = ( x1 , y1 , x2 ) => {
4343 const y2 = x1 + y1 - x2 ;
44- if ( x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0 ) return - Infinity ;
44+ if ( x1 < 0 || y1 < 0 || x2 < 0 || y2 < 0 ) return - 1 ;
4545 if ( grid [ y1 ] [ x1 ] === - 1 || grid [ y2 ] [ x2 ] === - 1 ) return - 1 ;
4646 if ( dp [ y1 ] [ x1 ] [ x2 ] !== - Infinity ) return dp [ y1 ] [ x1 ] [ x2 ] ;
4747
@@ -60,9 +60,45 @@ const cherryPickup = (grid) => {
6060 return dp [ y1 ] [ x1 ] [ x2 ] ;
6161 } ;
6262
63- return Math . max ( 0 , go ( n - 1 , n - 1 , n - 1 ) ) ;
63+ return Math . max ( go ( n - 1 , n - 1 , n - 1 ) , 0 ) ;
64+ } ;
65+
66+ /** 2) Dynamic Programming (Iteration) */
67+ const cherryPickup = ( grid ) => {
68+ if ( grid == null || grid . length === 0 ) return 0 ;
69+
70+ const n = grid . length ;
71+ const dp = [ ...new Array ( n + 1 ) ] . map ( ( ) =>
72+ [ ...new Array ( n + 1 ) ] . map ( ( ) =>
73+ Array ( n + 1 ) . fill ( - Infinity )
74+ ) ,
75+ ) ;
76+ dp [ 1 ] [ 1 ] [ 1 ] = grid [ 0 ] [ 0 ] ;
77+
78+ for ( let i1 = 1 ; i1 <= n ; i1 ++ ) {
79+ for ( let j1 = 1 ; j1 <= n ; j1 ++ ) {
80+ for ( let i2 = 1 ; i2 <= n ; i2 ++ ) {
81+ const j2 = i1 + j1 - i2 ;
82+ if ( i1 < 1 || j1 < 1 || i2 < 1 || j2 < 1 ) continue ;
83+ if ( grid [ i1 - 1 ] [ j1 - 1 ] === - 1 || grid [ i2 - 1 ] [ j2 - 1 ] === - 1 ) continue ;
84+
85+ const cur = Math . max (
86+ dp [ i1 - 1 ] [ j1 ] [ i2 ] ,
87+ dp [ i1 - 1 ] [ j1 ] [ i2 - 1 ] ,
88+ dp [ i1 ] [ j1 - 1 ] [ i2 ] ,
89+ dp [ i1 ] [ j1 - 1 ] [ i2 - 1 ] ,
90+ ) ;
91+
92+ if ( cur >= 0 ) {
93+ dp [ i1 ] [ j1 ] [ i2 ] = cur + grid [ i1 - 1 ] [ j1 - 1 ] ;
94+ if ( i1 !== i2 ) dp [ i1 ] [ j1 ] [ i2 ] += grid [ i2 - 1 ] [ j2 - 1 ] ;
95+ }
96+ }
97+ }
98+ }
99+ return Math . max ( dp [ n ] [ n ] [ n ] , 0 ) ;
64100} ;
65101
66- /** 2 ) Dynamic Programming (Optimized) */
102+ /** 3 ) Dynamic Programming (Optimized) */
67103// Time O(n^3)
68104// Space O(n^2)
0 commit comments