happy318
팽도리블로그
happy318
전체 방문자
오늘
어제
  • 전체글 (252)
    • 공부 (5)
      • Algorithm 정리 (0)
      • 논문리뷰 (1)
      • C++ (2)
      • Python (2)
      • Java (0)
      • Back-end (0)
      • Front-end (0)
      • Embedded (0)
    • 코딩테스트 (218)
      • Python 문제풀이 (100)
      • C++ 문제풀이 (108)
      • Python template (9)
      • C++ template (1)
    • 일상 (20)
      • 맛집 (13)
      • 쇼핑 (5)
      • 아무 일상 (2)
    • 게임 (9)
      • 메이플스토리 (9)

최근 글

인기 글

hELLO · Designed By 정상우.
happy318

팽도리블로그

코딩테스트/C++ 문제풀이

[백준] N과 M (12)

2022. 12. 10. 21:35

https://www.acmicpc.net/problem/15666

 

15666번: N과 M (12)

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

www.acmicpc.net

문제부터 간단하게 요약하면, 

 

중복 조합으로 숫자를 M개 뽑아서 오름차순으로 출력해야 하는 문제였습니다. 

 

<Solution>

DFS를 이용하여 구현하였습니다. 

코드는 아래와 같습니다. 

#include <iostream>
#include <algorithm>
#include <set>

using namespace std;

int N, M;
int num_array[10];
int num_array_[10];
int print_num[10];
int cur_index;

void getinput(){
    cin >> N >> M;
    int k ;
    for(int i = 0; i<N; i++){
        cin >> num_array[i];
    }
}

void dfs(int turn, int before_index){

    if(turn == M){
        // print num 
        for(int i = 0; i<M; i++){
            cout << print_num[i] << ' ';
        }
        cout << endl;
        return;

    }

    for(int i = before_index; i<cur_index; i++){
        print_num[turn] = num_array_[i];
        dfs(turn+1, i);
    }
    return;

}

void solution(){
    sort(num_array, num_array+N);
    // remove duplicate
    cur_index = 1;
    int before_val = num_array[0];
    num_array_[0] = num_array[0];
    for(int i = 1; i<N; i++){
        if(before_val == num_array[i]) continue;

        num_array_[cur_index++] = num_array[i];
        before_val = num_array[i];
    }

    dfs(0, 0);

}

int main(){
    getinput();

    solution();

    return 0;


}
반응형

'코딩테스트 > C++ 문제풀이' 카테고리의 다른 글

[백준] N과 M (9)  (0) 2022.12.25
[백준] Java vs C++  (0) 2022.12.18
[백준] 마라톤 1  (0) 2022.12.01
[백준] 공주님의 정원  (0) 2022.12.01
[백준] 경비원  (0) 2022.12.01
    '코딩테스트/C++ 문제풀이' 카테고리의 다른 글
    • [백준] N과 M (9)
    • [백준] Java vs C++
    • [백준] 마라톤 1
    • [백준] 공주님의 정원
    happy318
    happy318

    티스토리툴바