์กฐํ•ฉ

notion image
์ด๋ฏธ ๋ฝ‘์€ ๊ฑฐ ์ดํ›„๋กœ๋งŒ ๋Œ๋ฆฐ๋‹ค. [1,4]๋‚˜ [4,1]์ด๋‚˜ ๊ฐ™์œผ๋ฏ€๋กœ
ย 
notion image
notion image
for๋ฌธ์€ ๋ฝ‘๋Š” ๊ฐœ์ˆ˜๊ฐ€ ๋งŽ์•„์งˆ ๋•Œ ๋„ˆ๋ฌด ์ค‘์ฒฉ๋˜๋ฏ€๋กœ ์žฌ๊ท€๋กœ ๊ตฌํ˜„ํ•ด๋ณผ ์ˆ˜ ์žˆ๋‹ค.
idx๋Š” ํ˜„์žฌ ์œ„์น˜์— ๋Œ€ํ•œ ์ •๋ณด๋‹ค.
s๊ฐ€ ์„ ํƒ๋œ ๊ฐœ์ˆ˜์ธ๋ฐ s๊ฐ€ ์ฆ๊ฐ€ํ•˜๋‹ค๊ฐ€ r์ด ๋˜๋ฉด ์ถœ๋ ฅํ•˜๊ณ  return๋œ๋‹ค.
์žฌ๊ท€์ ์œผ๋กœ ํ˜ธ์ถœ๋  ๋•Œ๋งˆ๋‹ค ์„ ํƒ๋œ ๊ฐœ์ˆ˜ s๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๊ณ  ํ˜„์žฌ ์œ„์น˜ idx๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
idx๊ฐ€ ์ฆ๊ฐ€๋˜์—ˆ์œผ๋‹ˆ i๊ฐ’์— ํ• ๋‹น๋˜์–ด ๋ฐฐ์—ด์˜ ๊ฐœ์ˆ˜์—์„œ idx๋ฅผ ๋บ€ ๊ฐ’๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ์ž‘์„ ๋•Œ ๊ทผ๋ฐ ์ด ๋ฒ”์œ„ ์„ค์ •์ด ์ง๊ด€์ ์ด์ง€ ์•Š์•„์„œ ๋‚˜๋Š” ์•„๋ž˜์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ–ˆ์—ˆ๋‹ค.
ย 
function solution(n, m) {
    let answer = [];
    let tmp = Array.from({ length: m }, () => 0);
    let input = [10, 20, 30, 40];

    // * : ๋ ˆ๋ฒจ์ด m์ด ๋˜๋ฉด ๋ฉˆ์ถค(m๊ฐœ ๋ฝ‘์€ ๊ฒƒ, m๊ฐœ ๊ฐ€์ง€ ๋ป—์Œ), s๋Š” 1~4
    function DFS(L, s) {
        if (L === m) {
            answer.push(tmp.slice());
        } else {
            for (let i = s; i < n; i++) {
                tmp[L] = input[i];
                DFS(L + 1, i + 1);
            }
        }
    }
    DFS(0, 0);
    console.log(answer);
    return answer;
}
solution(4,2);
notion image
ย