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

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

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

์ธํ”„๋Ÿฐ

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

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


โœ๏ธIdea Sketch

2021-06-29

1. m๊ฐœ ๋ฝ‘์•„์„œ ๋‚˜์—ดํ•˜๊ธฐ

  • ์ค‘๋ณต ํ—ˆ์šฉX

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

  • DFS ๋งค๊ฐœ๋ณ€์ˆ˜ v : ๋ฝ‘๋Š” ํšŸ์ˆ˜
  • DFS(1); ์ดˆ๊ธฐ๊ฐ’
if (v > m) {
  console.log(res);
  return ;
}

3. DFS ๋กœ์ง

  • ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” for()
  • ๋ฐฉ๋ฒ• 1. arr.includes() ์‚ฌ์šฉ
for (let i=0; i<arr.length; i++) {
  if (!res.includes(arr[i])) {
    res.push(arr[i]);
    DFS(v+1);
    res.pop();
  }
}
  • ๋ฐฉ๋ฒ• 2. continue; ์‚ฌ์šฉ
for (let i = 0; i < arr.length; i++) {
  if (res.includes(arr[i])) continue;
  res.push(arr[i]);
  DFS(v + 1);
  res.pop();
}


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

2021-06-29

let m = 2;
let arr = [3, 6, 9];

let res = [];
let cnt = 0;

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

  for (let i = 0; i < arr.length; i++) {
    if (res.includes(arr[i])) continue;
    res.push(arr[i]);
    DFS(v + 1);
    res.pop();
  }
}

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