[10μ£Ό μμ± C++ μ½λ©ν μ€νΈ] νμκ°λ - μμ΄(Permutation), μ‘°ν©(Combination)
μμμ μκ΄ 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κ° μ΄νλ‘ λ½μ λ μΆμ². ꡬνμ΄ κ°λ¨ν¨.)