๐ฅ๋ฌธ์ ๋งํฌ
https://school.programmers.co.kr/learn/courses/30/lessons/12907
๐ฅ์ฒซ๋ฒ์งธ ํ์ด ( ํ ์คํธ ์ผ์ด์ค ๋ชจ๋ ํต๊ณผ but ์๊ฐ์ด๊ณผ )
์ฒ์์ ๋ด๊ฐ ์์ฑํ ์ฝ๋์ด๋ค. ( ํ๋จ ์ฐธ์กฐ )
์ด ์ฝ๋๋ ํ ์คํธ ์ผ์ด์ค๋ ๋ชจ๋ ํต๊ณผ์ง๋ง ์๊ฐ์ด๊ณผ ํ ์คํธ์์ ๋ชจ๋ ์๊ฐ์ด๊ณผ๊ฐ ๋์๋ค๐ญ
๋ค๋ฅธ์ฌ๋๋ค์ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํด๋ณด๋ ์ฌ๊ท๊ฐ ์๋ dp ( dynamic programming : ์ต์ ํ ) ๋ฌธ์ ์๋ ๊ฒ ๊ฐ๋ค.
function solution(n, money) {
let answer = 0;
money.sort((a,b)=>a-b)
const recursive =(rest,arr)=>{
if(arr.length===0 || rest <=0){
return
}
let fixed = arr.shift()
if(fixed>rest){
return
}
let count = 0;
while(1){
if((rest-fixed*count)>0){
let newArr = [...arr]
recursive(rest-fixed*count,newArr)
}else if((rest-fixed*count)===0){
++answer
return
}else{
return
}
++count
}
}
let sliced = money.slice(1)
let fixed = money[0]
recursive(n,money)
return answer%1000000007;
}
๐ฅ๋๋ฒ์งธ ํ์ด ( ๋ค๋ฅธ ์ฌ๋ ํ์ด ์ฐธ๊ณ )
์ฒซ๋ฒ์งธ ํ์ด์ ๋นํด newArr = [...arr]์ ๊ฐ์ด ๋ฐฐ์ด์ ๋ณต์ฌํ ํ์๋ ์๊ณ sort()ํ ํ์๋ ์๊ณ ์ฌ๊ท๋ฅผ ์ฌ์ฉํ ํ์๋ ์์ด ๊ณ์ฐํ์๊ฐ ํ์คํ ์ค์ด๋ ๋ค.
dp[n] ์ n์ ๋ง๋ค์ ์๋ ์ด ๊ฒฝ์ฐ์ ์๋ฅผ ์๋ฏธํ๋ค.
์๋ ์ฝ๋๋ฅผ ๋ณด๊ณ ์ฐ์ฐ๊ณผ์ ์ ๊ณฑ์น์ด ๋ณด์!
function solution(n, moneyList) {
let dp = Array(n+1).fill(0)
dp[0]=1
for(const money of moneyList){
for(let i=money; i<n+1; ++i){
dp[i] = dp[i] + dp[i-money]
}
}
return dp[n]%1000000007
}
๐ฅ์ฐธ๊ณ
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค[JS] > [PCCP ๊ธฐ์ถ๋ฌธ์ ] 2๋ฒ / ํผ์ฆ ๊ฒ์ ์ฑ๋ฆฐ์ง (1) | 2024.09.11 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค[JS] > [PCCP ๊ธฐ์ถ๋ฌธ์ ] 3๋ฒ / ์ถฉ๋์ํ ์ฐพ๊ธฐ (0) | 2024.09.11 |
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ๋ฆฌ์ฝ์ณ ๋ก๋ด (0) | 2024.08.25 |
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ๊ดํธ ๋ณํ ( 2020 KAKAO BLIND RECRUITMENT ) (0) | 2024.08.24 |
ํ๋ก๊ทธ๋๋จธ์ค[JS] > ์ด๋ชจํฐ์ฝ ํ ์ธํ์ฌ (0) | 2024.08.24 |