백준 문제/백트래킹

[백준] 15652번 N과 M(4)

dubu0721 2025. 1. 27. 11:48

문제: 15652번: N과 M (4)

basic-algo-lecture/workbook/0x0C.md at master · encrypted-def/basic-algo-lecture

 

basic-algo-lecture/workbook/0x0C.md at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com

 

#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iomanip> // setprecision을 사용하기 위한 헤더
#include <climits>
#include <list>

using namespace std;

int n, m;
int curNums[8]; // 현재 수열의 상태(8개가 max)

void Funct(int functM) {
	// 현재 수열의 크기가 m 과 같으면 이제 출력하고 돌아가!
	if (functM == m) {
		for (int i = 0; i < m; i++) {
			cout << curNums[i] << " ";
		}
		cout << "\n";
		return;
	}

	int start = 1; // 일단 기본값 1
	if (functM != 0)
		start = curNums[functM - 1];

	for (int i = start; i <= n; i++) {
		curNums[functM] = i; // 수열에 넣기

		Funct(functM + 1);
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> n >> m;
	Funct(0);

	return 0;
}

 

수열의 특징이 중복 가능에 오름차순이라고 문제에서 줬다. 중복 가능이니까 방문 처리 신경쓰지 않아도 된다. 그런데 오름차순이니까 반복문 돌 때 i 를 1로 시작하면 안 되고 현재 수열의 맨 마지막 값으로 시작해야 한다.

 

 

 

참고자료:

BaaaaaaaarkingDog | [실전 알고리즘] 0x0C강 - 백트래킹

 

[실전 알고리즘] 0x0C강 - 백트래킹

이번에는 백트래킹을 배워보도록 하겠습니다. 백트래킹도 재귀와 더불어 많은 사람들이 고통을 호소하는 알고리즘 중 하나이지만 의외로 그 재귀적인 구조에 매료되어서 참재미를 알아버리는

blog.encrypted.gg