C++ ์ˆœ์—ด(permutation)๊ณผ ์กฐํ•ฉ(combination)

2023. 2. 1. 22:23ใ†๐Ÿ“š Algorithm/๐Ÿ‘€ C++ ๋ฌธ์ œ ํ’€์ด

๋ฐ˜์‘ํ˜•

์ˆœ์—ด(Permutation)์ด๋ž€?

์ˆœ์„œ๊ฐ€ ์ •ํ•ด์ง„ ์ž„์˜์˜ ์ง‘ํ•ฉ์„ ๋‹ค๋ฅธ ์ˆœ์„œ๋กœ ์„ž๋Š” ์—ฐ์‚ฐ

 

ex) n๊ฐœ์˜ ์ง‘ํ•ฉ ์ค‘ n ๊ฐœ๋ฅผ ๊ณจ๋ผ๋ผ

 

์ˆ˜ํ•™ ๊ณต์‹ ) nPr = n! / (n-r)!

 

 

์ˆœ์—ด ๊ตฌํ˜„ํ•˜๊ธฐ

1. next_permutation / prev_permutation

next_permutation : ์˜ค๋ฆ„์ฐจ์ˆœ ๋ฐฐ์—ด ๊ธฐ๋ฐ˜

prev_permutation : ๋‚ด๋ฆผ์ฐจ์ˆœ ๋ฐฐ์—ด ๊ธฐ๋ฐ˜

 

next_permutation([first, last))

- first : ์ˆœ์—ด์„ ์‹œ์ž‘ํ•  ๋ฒ”์œ„์˜ ์ฒซ๋ฒˆ์งธ ์ฃผ์†Œ

- last : ํฌํ•จ๋˜์ง€ ์•Š์€ ๋งˆ์ง€๋ง‰ ์ฃผ์†Œ

 

#include <vector>
#include <algorithm>
#include <iostream>


void printV(vector<int> &v) {
	for(int i = 0; i < v.size(); i++) {
		cout << v[i] << ' ';
	}
	cout << '\n';
}

...


for (int i = 1; i <= 3; i++) {
	v.push_back(i);
}

do {
	printV(v);
} while(next_permutation(v.begin(), v.end()));

 

๋งŒ์•ฝ ๋ฐฐ์—ด์˜ ํŠน์ • ๋ถ€๋ถ„๋งŒ ์ด์šฉํ•ด์„œ ์ˆœ์—ด์„ ๊ตฌํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด?

- next_permutation(v.begin(), v.begin() + 3);

 

 

์ฃผ์˜ํ• ์  !!)

- prev ๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ,

- next ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ ์‚ฌ์šฉํ•ด์•ผ ํ•จ!

 

 

2. ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ์ˆœ์—ด

void makePermutation (int n, int r, int depth) {
	cout << n << " : " << r << " : " << depth << "\n";
	if (r == depth) {
		printV(v);
		return;
	}

	for(int i = depth; i <n; i++) {
		swap(v[i], v[depth]);
		makePermutation(n, r, depth + 1);
		swap(v[i], v[depth]);
	}
	return;
}

 

์ฃผ์˜ํ• ์  !!) ์žฌ๊ท€ํ•จ์ˆ˜๋Š” ์ข…๋ฃŒ ์กฐ๊ฑด์ด ํ•„์š”ํ•˜๋‹ค

 

 

 

 

 

 

์กฐํ•ฉ(Permutation)์ด๋ž€?

์ˆœ์„œ ์ƒ๊ด€์—†์ด ๋‹ค๋ฅธ ์ˆœ์„œ๋กœ ์„ž๋Š” ์—ฐ์‚ฐ

 

์ˆ˜ํ•™ ๊ณต์‹ ) nCr = n! / [r! * (n-r)!]

 

์กฐํ•ฉ ๊ตฌํ˜„ํ•˜๊ธฐ

1. ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ์กฐํ•ฉ

void print(vector<int> b) {
	for(int i : b) cout << i << " ";
	cout << "\n";
}

void combi(int start, vector<int> b) {
	if (b.size() == k) {
		print(b);
		return;
	}
for (int i = start + 1; i < n; i++) {
	b.push_back(i);
	combi(i, b);
	b.pop_back();
}
return; 
}

 

 

 

2. ์ค‘์ฒฉ for ๋ฌธ์„ ์ด์šฉํ•œ ์กฐํ•ฉ

3๊ฐœ ์ด์ƒ ๋ฝ‘๋Š” ๊ฒฝ์šฐ์—๋Š” ์ค‘์ฒฉ for ๋ฌธ ๋ณด๋‹ค ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์ž 

for (int i = 0; i <n; i++) {
	for(int j = i+1; j <n; j++) {
		for(int k = j+1; k <n; k++) {
			cout << i << j << '\n';
		}
	}
}

 

 

 

์กฐํ•ฉ ํŠน์ง•!)

nCr = nC(n-r) ์€ ๋™์ผํ•˜๋‹ค

ex) 9๊ฐœ ์ค‘ 2๊ฐœ ๋ฝ‘๋Š” ๋ฐฉ๋ฒ•๊ณผ 9๊ฐœ ์ค‘ 7๊ฐœ ๋ฝ‘๋Š” ๋ฐฉ๋ฒ•์ด ๋™์ผ

์ฆ‰, 9๊ฐœ ์ค‘ 7๊ฐœ ๋ฝ‘๋Š” ๋ฌธ์ œ ๋‚˜์˜ค๋ฉด -> 9๊ฐœ ์ค‘ 2๊ฐœ ๋ฝ‘์•„์„œ ์ œ๊ฑฐํ•˜๋ฉด ๋œ๋‹ค

 

 

๋ฐ˜์‘ํ˜•