๋ฌธ์ ๋งํฌ
์ฃผ์ด์ง ์ ์ ๋ฐฐ์ด nums์ ์์๋ค์ ์ฌ์ฉํ์ฌ target์ ๋ง๋๋ ๋ฐฉ๋ฒ์ ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
๊ฐ ์์๋ค์ ์ค๋ณต์ผ๋ก ์ฌ์ฉํ ์ ์๊ณ ์์ด ๋ฐฉ์์ ๋ฐ๋ฅธ๋ค. (1,3)๊ณผ (3,1)์ ๋ค๋ฅธ ๊ฒฝ์ฐ๋ก ๋ด
์ ๊ทผ ๋ฐฉ๋ฒ
์ ํ์ ์ธ dp๋ฌธ์ ๋ก ์ด๋ฒ dp์ ํต์ฌ์ dp[n] => n์ ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์ ์๋ ์ ์ด๋ค.
1 ~ target๊น์ง dp[n]์ ๊ตฌํ๊ณ (dp[1] === 1์ ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์ ์, dp[2] === 2๋ฅผ ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์ ์...)
๋ง์ฝ dp[5]๋ฅผ ๊ตฌํ๋๋ฐ ํ์ฌ num์ 2์ด๊ณ , dp[3]์ ๋ง๋๋ ๋ฐฉ๋ฒ์ด 3๊ฐ๋ผ๋ฉด
dp[5] += dp[5 - 2] ๋ผ๋ ๊ฐ๋ ์ด ๊ฐ๋ฅํ ๊ฒ ์ด๋ค. (dp[3]์ ๋ง๋๋ ๋ฐฉ๋ฒ์ด 3๊ฐ๊ณ , ํ์ฌ num์ 2์ด๋ฏ๋ก dp[5]์๋ 3๊ฐ์ง ๋ฐฉ๋ฒ์ด ์ถ๊ฐ๋ ์ ์๋ค.)
for(let curTarget = 1; curTarget <= target; curTarget++){ for(let num of nums){ if((curTarget - num) >= 0){ if(curTarget === num){ dp[curTarget] += 1; }else{ dp[curTarget] += dp[curTarget - num]; } } } }โ
์ฝ๋๋ก ๊ตฌํํ๋ฉด ์ด๋ ๊ฒ ๋๋ค.
curTarget์ 1 ~ target๊น์ง ์ํํ๋ฉฐ ํ์ฌ ๊ฐ์ target์ด๋ผ ์๊ฐํ๊ฒ ๋ค๋ ์๋ฏธ์ ๋ณ์์ด๊ณ
curTarget์ด nums์ ์์๋ณด๋ค ์๋ค๋ฉด ๊ฐ๋ฅํ์ง ์์ ๊ฒฝ์ฐ์ด๋ฏ๋ก ๋ค์ for๋ฌธ์ผ๋ก ๋์ด๊ฐ๋ค.
๋ํ dp[curTarget]์ธ ๊ฒฝ์ฐ๋ ๋จ์ํ๊ฒ 1์ ์ถ๊ฐํด์ฃผ๊ณ ,
์์ ์ดํด๋ณธ๋๋ก ๋ง์ฝ curTarget - num >= 0์ด๊ณ , curTarget !== num์ธ ๊ฒฝ์ฐ dp[curTarget] += dp[curTarget - num]์ ์ถ๊ฐํด์ค๋ค.
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var combinationSum4 = function(nums, target) {
const dp = new Array(target + 1).fill(0);
dp[0] = 0;
for(let curTarget = 1; curTarget <= target; curTarget++){
for(let num of nums){
if((curTarget - num) >= 0){
if(curTarget === num){
dp[curTarget] += 1;
}else{
dp[curTarget] += dp[curTarget - num];
}
}
}
}
return dp[target]
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Reduce Array Size to The Half (0) | 2022.08.18 |
---|---|
[LeetCode] Unique Morse Code Words (0) | 2022.08.17 |
[LeetCode] My Calendar I (0) | 2022.08.03 |
[LeetCode] Kth Smallest Element In A Sorted Matrix (0) | 2022.08.02 |
[LeetCode] Unique Paths (0) | 2022.08.01 |