File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ function coinChange ( coins : number [ ] , amount : number ) : number {
2
+ /* # Solution 1: BFS
3
+ * ์ต์ ๊ฒฝ๋ก๋ฅผ ์ฐพ๋ ๋ฌธ์ => BFS
4
+ * ํ์ฌ๊น์ง ์ฌ์ฉํ ๋์ ์ ๊ฐ์์ ํ์ฌ๊น์ง ์ฌ์ฉํ ๋์ ์ ํฉ์ queue์ ๋ฃ๋๋ค.
5
+ * visited: ์ค๋ณต ๋ฐฉ๋ฌธ์ ๋ฐฉ์งํ๊ธฐ ์ํ set
6
+ * ๋์ ์ก์ด amount์ ๊ฐ์์ง๋ฉด count๋ฅผ return
7
+ * visited์ ๋์ ์ก์ด ์์ผ๋ฉด continue
8
+ * coins๋ฅผ ์ํํ๋ฉด์ ๋์ ์ก์ ๋์ ์ ๋ํ ๊ฐ์ด amount๋ณด๋ค ์์ผ๋ฉด queue์ ๋ฃ๋๋ค.
9
+ * queue๊ฐ ๋น๋๊น์ง ๋ฐ๋ณต
10
+ * ํ๊ฐ ๋น์ด์๊ณ amount๋ฅผ ๋ง๋ค์ ์์ผ๋ฉด -1์ return
11
+ */
12
+ const queue = [ [ 0 , 0 ] ] ; // [number of coins, accumulated amount]
13
+ const visited = new Set ( ) ;
14
+
15
+ while ( queue . length > 0 ) {
16
+ const [ count , total ] = queue . shift ( ) ;
17
+ if ( total === amount ) {
18
+ return count ;
19
+ }
20
+ if ( visited . has ( total ) ) {
21
+ continue ;
22
+ }
23
+ visited . add ( total ) ;
24
+ for ( const coin of coins ) {
25
+ if ( total + coin <= amount ) {
26
+ queue . push ( [ count + 1 , total + coin ] ) ;
27
+ }
28
+ }
29
+ }
30
+ return - 1 ;
31
+ // TC: ๊ฐ ๊ธ์ก(amount)๋ง๋ค ๋์ (coins)์ ์ํํ๋ฏ๋ก O(N*M) N: amount, M: coins.length
32
+ // SC: O(N) N: amount
33
+ }
You canโt perform that action at this time.
0 commit comments