https://yabmoons.tistory.com/123?category=838490
[ 순열과 조합 구현 ] 재귀를 통한 구현(4 - 중복순열) (C++)
지난 글에서 중복조합에 대해서 알아보았다. 이번 시간에는 중복 순열에 대해서 알아보도록 하자. [ 조합 알아보기(Click) ] [ 순열 알아보기(Click) ] [ 중복조합 알아보기(Click) ] 중복순열을 알아보기전, 먼저..
yabmoons.tistory.com
1 2 3에서 2개를 뽑는경우
순열: 1 2, 1 3, 2 1, 2 3, 3 1, 3 2
중복 순열: 1 1, 1 2, 1 3, 2 1, 2 2, 2 3, 3 1, 3 2, 3 3
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
|
#include <bits/stdc++.h>
using namespace std;
int n, m, a[10], s[10];
void solve(int cnt) {
if(cnt == m) {
for(int i = 0; i < m; i++)
cout << s[i] << ' ';
cout << '\n';
return;
}
for(int i = 0; i < n; i++) {
s[cnt] = a[i];
solve(cnt + 1);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for(int i = 0; i < n; i++) a[i] = i + 1;
solve(0);
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
내 나름대로의 코드도 구현해봤다.
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
|
#include <bits/stdc++.h>
using namespace std;
int n, m, a[10];
void solve(int idx) {
if(idx == m) {
for(int i = 0; i < m; i++)
cout << a[i] << ' ';
cout << '\n';
return;
}
for(int i = 1; i <= n; i++) {
a[idx] = i;
solve(idx + 1);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
solve(0);
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|