๐Ÿ“ Coding Test Study/C++

[10์ฃผ ์™„์„ฑ C++ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ] ํ•„์ˆ˜๊ฐœ๋… - ์ˆœ์—ด(Permutation), ์กฐํ•ฉ(Combination)

ibelieveinme 2023. 8. 3. 18:25
728x90

์ˆœ์„œ์™€ ์ƒ๊ด€ O ๋ฝ‘๋Š”๋‹ค๋ฉด >> ์ˆœ์—ด

์ˆœ์„œ์™€ ์ƒ๊ด€ X ๋ฝ‘๋Š”๋‹ค๋ฉด >> ์กฐํ•ฉ

 

์ˆœ์„œ๋ฅผ ์žฌ๋ฐฐ์น˜ํ•˜์—ฌ ...

~ํ•œ ์ˆœ์„œ์˜ ๊ฒฝ์šฐ max ๊ฐ’์„ ๊ตฌํ•˜์‹œ์˜ค ๋“ฑ๋“ฑ์˜ ๋ฌธ์ œ >> ์ˆœ์—ด !


* ์ˆœ์—ด ํ•จ์ˆ˜

next_permutation(์˜ค๋ฆ„์ฐจ์ˆœ)

prev_permutation(๋‚ด๋ฆผ์ฐจ์ˆœ)

 

* ์˜ˆ์‹œ ์ฝ”๋“œ

#include <bits/stdc++.h>
using namespace std; 

int main() { 
    int a[] = {1,2,3};
    do{
        for(int i : a) cout << i << " ";
        cout << "\n";
    } while(next_permutation(&a[0], &a[0] + 3)); // from, to
    return 0; 
}

๊ฒฐ๊ณผ

1 2 3 
1 3 2 
2 1 3 
2 3 1 
3 1 2 
3 2 1 

 

#include <bits/stdc++.h>
using namespace std; 

int main() { 
    int a[] = {1,2,3};
    do{
        for(int i : a) cout << i << " ";
        cout << "\n";
    } while(next_permutation(a, a + 3)); // from, to
    return 0; 
}

&a[0] ์ด๋ ‡๊ฒŒ ์•ˆ์“ฐ๊ณ  a ๋งŒ ์จ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค.

#include <bits/stdc++.h>
using namespace std; 

int main() { 
    vector<int> a = {2,1,3};
    
    sort(a.begin(), a.end());
    do{
        for(int i : a) cout << i << " ";
        cout << "\n";
    } while(next_permutation(a.begin(), a.end())); // from, to
    
    return 0; 
}

๋ฒกํ„ฐ์ธ ๊ฒฝ์šฐ begin, end ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ํ˜ธ์ถœํ•œ๋‹ค.

์ˆœ์„œ์ •๋ ฌ์ด ์•ˆ๋˜์–ด ์žˆ๋‹ค๋ฉด ๊ทธ ๋‹ค์Œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ถ€ํ„ฐ ๊ตฌํ•ด์ง€๋ฏ€๋กœ ์ˆœ์—ดํ•จ์ˆ˜ ์‚ฌ์šฉ ์ „์— ์ •๋ ฌ์„ ๊ผญ ํ•ด์•ผ ํ•œ๋‹ค.

๊ฒฝ์šฐ์˜ ์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๊ณต์‹๋„ ์•Œ์•„๋‘์ž.

* ์กฐํ•ฉ

[์กฐํ•ฉ ๊ฒฝ์šฐ์˜ ์ˆ˜ ๊ฐœ์ˆ˜๊ตฌํ•˜๋Š” ๊ณต์‹]

 

[๊ตฌํ˜„๋ฐฉ๋ฒ•]

1) ์žฌ๊ท€ํ•จ์ˆ˜(4๊ฐœ ์ด์ƒ ๋ฝ‘์„ ๋•Œ ์ถ”์ฒœ) ์•”๊ธฐโ˜…โ˜…โ˜…โ˜…โ˜…

#include <iostream>
#include <vector>
using namespace std;

int n = 5, k = 3, a[5] = { 1, 2, 3, 4, 5 }; // 5C3

void print(vector<int> v) {
	for (int i : v) cout << a[i] << " ";
	cout << "\n";
}

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

int main() {
	vector<int> v;
	combi(-1, v);
	return 0;
}

 

2) ์ค‘์ฒฉ for๋ฌธ(3๊ฐœ ์ดํ•˜๋กœ ๋ฝ‘์„ ๋•Œ ์ถ”์ฒœ. ๊ตฌํ˜„์ด ๊ฐ„๋‹จํ•จ.)

 

 

728x90