Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
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
Tags
more
Archives
Today
Total
관리 메뉴

Mini

백준 15657 N과 M(8) c++ // 중복조합 구현방법 본문

Algorithm/back_tracking

백준 15657 N과 M(8) c++ // 중복조합 구현방법

Mini_96 2023. 10. 3. 00:42

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

 

15657번: N과 M (8)

N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. N개의 자연수는 모두 다른 수이다. N개의 자연수 중에서 M개를 고른 수열

www.acmicpc.net

1. 핵심로직

1 .1. 방문부분 주석 => 중복구현

1. 2. start=arr[k-1] // (이전에 저장된인덱스) 부터 시작 => 조합구현

 

2. 전체코드

#include <bits/stdc++.h>
using namespace std;

int n,m;
int num[10],arr[10];
int isused[10];

//현재까지 k개의 수를 선택함.
void go(int k) {
	if (k==m){
		for (int i = 0; i < m; ++i) {
			cout << num[arr[i]] << " ";
		}
		cout << "\n";
		return;
	}

	//스타트=> 조합구현
	int st = 0;
	if (k != 0) st = arr[k - 1];

	for (int i = st; i < n; ++i) {
		//if (isused[i]) continue;
		arr[k] = i;	//arr에 인덱스를 기록, return에서 인덱스로 접근하면됨.
		isused[i] = 1;
		go(k+1);
		isused[i] = 0;
	}

}


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

	cin >> n>>m;
	for (int i = 0; i < n; ++i) {
		cin >> num[i];
	}
	sort(num,num+n);	//정렬 end 제한 => 입력안된 0초기값 정렬안되게

	go(0);
}