File tree Expand file tree Collapse file tree 1 file changed +7
-28
lines changed Expand file tree Collapse file tree 1 file changed +7
-28
lines changed Original file line number Diff line number Diff line change 1
1
const coinChange = function ( coins , target ) {
2
- if ( target === 0 ) return 0 ;
2
+ const dp = new Array ( target + 1 ) . fill ( target + 1 ) ;
3
3
4
- let level = 0 ;
5
- let found = false ;
6
-
7
- let queue = [ ...coins ] ;
8
- let visit = new Set ( coins ) ;
9
-
10
- while ( queue . length > 0 ) {
11
- level ++ ;
12
-
13
- const queueLength = queue . length ;
14
- for ( let i = 0 ; i < queueLength ; i ++ ) {
15
- const sum = queue . shift ( ) ;
16
-
17
- if ( sum === target ) {
18
- found = true ;
19
- break ;
20
- }
21
-
22
- for ( let j = 0 ; j < coins . length ; j ++ ) {
23
- if ( sum + coins [ j ] > target || visit . has ( sum + coins [ j ] ) ) continue ;
24
- queue . push ( sum + coins [ j ] ) ;
25
- visit . add ( sum + coins [ j ] ) ;
4
+ dp [ 0 ] = 0 ;
5
+ for ( let i = 1 ; i <= target ; i ++ ) {
6
+ for ( let j = 0 ; j < coins . length ; j ++ ) {
7
+ if ( i >= coins [ j ] ) {
8
+ dp [ i ] = Math . min ( dp [ i ] , 1 + dp [ i - coins [ j ] ] ) ;
26
9
}
27
10
}
28
-
29
- if ( found ) break ;
30
11
}
31
-
32
- if ( found ) return level ;
33
- else return - 1 ;
12
+ return dp [ target ] === target + 1 ? - 1 : dp [ target ] ;
34
13
} ;
35
14
36
15
console . log ( coinChange ( [ 1 , 2 , 5 ] , 11 ) ) ; //3
You can’t perform that action at this time.
0 commit comments