Pepperminttt
Pepperminttt's Dev
Pepperminttt
전체 방문자
오늘
어제
  • devInfo (86)
    • forBeingGoodDeveloper (2)
    • React (2)
      • LostArk Open API (1)
    • algorithm (58)
      • problems (44)
      • theory (14)
    • computerScience (8)
      • network (8)
    • javaScript (8)
    • Java (4)
    • web (2)
      • webApplication (2)
    • etc. (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 프로그래머스
  • DP문제
  • solved.ac
  • 알고리즘
  • 탐욕법
  • Java
  • node.js
  • greedy
  • 그래프
  • JavaScript
  • dfs
  • Network
  • dfs문제
  • BFS
  • C++
  • DP
  • 벨만-포드
  • 백준
  • bfs문제
  • 탐욕법 문제

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Pepperminttt

Pepperminttt's Dev

순열/조합 (Permutation / Combination)
algorithm/theory

순열/조합 (Permutation / Combination)

2022. 11. 5. 19:00

1. Combination (조합)

조합 : 순서 없이 n개 중에 r개를 뽑는 것

  • 예) 10C3 = 1098 / 321 = 120
  • nCr = nCn-r이므로 10C3 = 10C7
const getCombinations = (array, selectNumber) => {
    const results = [];
    if(selectNumber === 1){
        return array.map((element) => [element]);
    }
    array.forEach((fixed, index, origin) => {
        const rest = origin.slice(index+1);
        const combinations = getCombinations(rest, selectNumber - 1);
        const attached = combinations.map((combination) => [fixed, ...combination]);
        results.push(...attached);
    });
    return results;
}
console.log(getCombinations([1,2,3,4], 3));

주어진 수가 1,2,3,4 이고 이 중 3개를 조합으로 뽑는다고 했을 때, 문제 해결 전략은 다음과 같습니다.

 

1,2,3,4 중에서 3개 조합 구하기 => 숫자 하나를 정한 다음, 나머지 중에서 2개 조합 구함 => 하나를 정하고 나머지 중에서 1개 조합 구함

 

(이 때 숫자 하나를 정하면, 나머지가 다음 차례에 있는 수 중에서만 구성된다. 2를 정했으면 나머지가 3,4가 되는 것이지 1,3,4가 될 수는 없는 것)


2. Permutation (순열)

  • 순열 : n개 중에 r개를 뽑아서 순서대로 나열하는 것
    • 예 ) 10P3 = 1098 = 720
const getPermutations = (array, selectNumber) => {
  const results = [];
  if (selectNumber === 1) {
    return array.map((element) => [element]);
  }
  array.forEach((fixed, index, origin) => {
    const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
    const permutations = getPermutations(rest, selectNumber - 1);
    const attached = permutations.map((permutation) => [fixed, ...permutation]);

    results.push(...attached);
  });
  return results;
};

순열은 rest 배열을 구하는 방식만 다르고 매커니즘은 같습니다.

 

 

> 순열 관련 문제

> 조합 관련 문제

'algorithm > theory' 카테고리의 다른 글

플로이드 와샬(Floyd Warshall) 알고리즘  (0) 2023.07.21
소수(Prime number) 판별법/ javaScript  (0) 2023.06.01
탐욕법(Greedy)  (0) 2022.11.05
해쉬(Hash)  (0) 2022.11.05
BFS/DFS(Breadth/Depth First Search)  (0) 2022.11.05
    'algorithm/theory' 카테고리의 다른 글
    • 플로이드 와샬(Floyd Warshall) 알고리즘
    • 소수(Prime number) 판별법/ javaScript
    • 탐욕법(Greedy)
    • 해쉬(Hash)
    Pepperminttt
    Pepperminttt
    HTML, JavaScript, Python 등 Computer language TIL

    티스토리툴바