2019년 4월 13일 토요일

# N개의 문자를 N개로 늘어놓는 순열 과 모든 조합을 구하는 방법.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <vector>
using namespace std;
void DoPermutation(int charsSize, int level, char* numbers, bool* isUsed, vector<char>* perm);
void DoAllCombination(int charsSize, char* chars, int start, vector<char>* combi);
void PrintItems(vector<char>* items);

int main()
{
 vector<char> combi;
 vector<char> perm;
 char chars[4] = { 'a', 'b','c', 'd' };
 bool isUsed[4] = { false };

 cout << "N개 문자로 N개로 늘어놓는 모든 순열 출력" << endl;
 DoPermutation(4, 0, chars, isUsed, &perm);
 cout << "=========================================" << endl;
 cout << "N개 문자로 생성할 수 있는 모든 조합 출력." << endl;
 DoAllCombination(4, chars, 0, &combi);

 combi.clear();
 perm.clear();
 return 0;

}

// N개의 문자를 N개로 늘어놓을 수 있는 모든 순열을 출력합니다. 
void DoPermutation(int charsSize, int level, char* chars, bool* isUsed, vector<char>* perm) {
 
 if (level == charsSize) {
  PrintItems(perm);
 }

 for (int i = 0; i < charsSize; i++) {
  if (!isUsed[i]) {
   isUsed[i] = true;
   perm->push_back(chars[i]);
   DoPermutation(charsSize, level + 1, chars, isUsed, perm);
   perm->pop_back();
   isUsed[i] = false;
  }
 }
}

// N개의 문자로 만들 수 있는 모든 조합을 출력합니다.
void DoAllCombination(int charsSize, char* chars, int start, vector<char>* combi) {
 if (start == charsSize) {
  return;
 } 

 for (int i = start; i < charsSize; i++) {
  combi->push_back(chars[i]);
  PrintItems(combi);
  DoAllCombination(charsSize, chars, i+1 , combi);
  combi->pop_back();
 }
}

void PrintItems(vector<char>* items) {
 for (char c : *items) {
  cout << c;
 }
 cout << endl;
}

댓글 없음:

댓글 쓰기