์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜8] ์ค‘๋ณต์ˆœ์—ด ๊ตฌํ•˜๊ธฐ (Javascript)

์€์ง„ 2021. 6. 29. 17:38

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜8] ์ค‘๋ณต์ˆœ์—ด ๊ตฌํ•˜๊ธฐ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-29

1. 1๋ถ€ํ„ฐ N๊นŒ์ง€ ์ˆซ์ž ์ค‘ M๋ฒˆ์„ ๋ฝ‘๊ธฐ

  • ์ค‘๋ณตํ—ˆ์šฉ : ๋ฝ‘์•˜๋˜ ์ˆซ์ž๋ฅผ ๋˜ ๋ฝ‘์Œ
  • ๋‹ค ๋ฝ‘์œผ๋ฉด cnt++

2. DFS ์ข…๋ฃŒ์กฐ๊ฑด

  • m์ด ๊ธฐ์ค€
  • DFS์˜ ๋งค๊ฐœ๋ณ€์ˆ˜ v : ์ˆซ์ž๋ฝ‘์€ ํšŸ์ˆ˜
if (v > m) {
  cnt++;
  console.log(res);
  return;
}

3. ๋ฝ‘์•˜๋˜ ์ˆซ์ž๋ฅผ ๋˜ ๋ฝ‘๋Š” ๋กœ์ง

  • ์ง€๊ธˆ๊นŒ์ง€๋Š” ๋ฝ‘์€ ๊ฒฝ์šฐ/์•ˆ๋ฝ‘์€ ๊ฒฝ์šฐ ๋‘ ๊ฐ€์ง€๋กœ๋งŒ ํŒŒ์ต
  • ์ง€๊ธˆ์€ ์ˆœ์„œ๋Œ€๋กœ ํ•˜๋‚˜์”ฉ ๋ฝ‘์•„์•ผ ํ•จ --> for ๋ฐ˜๋ณต๋ฌธ?
for (let i=1; i<=n; i++) {
  res.push(i);
  DFS(v+1);
  res.pop();
}

4. ์ถœ๋ ฅํ˜•์‹

console.log(res.join(' ');


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-29

let n = 3, m = 2;
let cnt = 0;
let res = [];

function DFS(v) {
  if (v > m) {
    cnt++;
    console.log(res.join(' '));
    return;
  }

  for (let i = 1; i <= n; i++) {
    res.push(i);
    DFS(v + 1);
    res.pop();
  }
}

DFS(1);
console.log(cnt);