본문 바로가기
programming/baekjoon

15650 - N과 M (2)

by Ryuuu 2020. 8. 27.

문제

자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.

  • 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열
  • 고른 수열은 오름차순이어야 한다.

입력

첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8)

출력

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.

수열은 사전 순으로 증가하는 순서로 출력해야 한다.

풀이

재귀를 연습하기 좋다.

두가지 풀이로 풀어보았다.

1. 오름차순이므로 시작하는 부분 재귀함수로 넘겨줘 풀이

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
#include<iostream>
#include<string>
#include<algorithm>
#include<math.h>
#include<vector>
 
using namespace std;
 
bool c[10] = {};
vector<int> a;
void seq(int st, int index, int n, int m) { //n개중 m개 선택
    int i;
 
    if (index == m) {
        for (i = 0; i < m; i++) {
            cout << a[i] << ' ';
        }
        cout << '\n';
        return;
    }     
 
    for (i = st; i <= n; i++) {
        if (c[i]) continue;
 
        c[i] = true;
        a.push_back(i);
        seq(i+1,index + 1, n, m);
        c[i] = false;
        a.pop_back();
    }
     
}
 
int main() {
 
    int n, m;
 
    cin >> n >> m;
 
    seq(1, 0, n, m);
 
}

 

2. 특정 수를 기준으로 수열에 포함되는지 안되는지 판단

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
#include<iostream>
#include<string>
#include<algorithm>
#include<math.h>
#include<vector>
 
using namespace std;
 
bool c[10] = {};
vector<int> a;
void seq(int cnt, int index, int n, int m) { //n개중 m개 선택     cnt 갯수 index 시작점
 
    int i;
 
    if (cnt == m) {
        for (i = 0; i < m; i++) {
            cout << a[i] << ' ';
        }
        a.pop_back();
        cout << '\n';
        return;
    }
     
    if (index > n) {
        if (a.empty()) return;
        a.pop_back();
        return;
    }
 
 
    a.push_back(index);
    seq(cnt + 1, index + 1, n, m);          //포함될때(갯수 + 1, 시작점 + 1)
    seq(cnt, index + 1, n, m);              //포함안될때(시작점 + 1)
 
 
}
 
int main() {
 
    int n, m;
 
    cin >> n >> m;
 
    seq(0, 1, n, m);
 
}

'programming > baekjoon' 카테고리의 다른 글

1874 - 스택 수열  (0) 2020.08.27
9012 - 괄호  (0) 2020.08.27
9093 - 단어 뒤집기  (0) 2020.08.27
10828 - 스택  (0) 2020.08.27
백준 - 1260 dfs와 bfs  (1) 2020.05.21

댓글