백준 15657 N과 M(8)

aiden·2025년 11월 2일

백준 문제풀이

목록 보기
3/11

문제:
https://www.acmicpc.net/problem/15657

내 풀이:

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

int n, m;
int arr[9];
int answer[9];

void backtrack(int depth, int start_index) {
	if (depth == m) { // 제시된 길이만큼 만들기
		for (int i = 0; i < m; i++) {
			cout << answer[i] << " "; // 만들어진 배열 출력
		}
		cout << endl;
	}
	else {
		for (int i = start_index; i < n; i++) { // 어차피 비내림차순 출력이므로..
			answer[depth] = arr[i];

			backtrack(depth + 1, i); // 재귀호출
		}
	}
}
int main() {

	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
	}

	sort(arr, arr + n);
	backtrack(0, 0);


}

백트래킹을 사용하면 되는 간단한 문제다.

비내림차순 출력 조건은 sort 함수를 사용해 정렬하면 된다.

profile
All's well that ends well

0개의 댓글