본문 바로가기
알고리즘&자료구조/백트레킹

백준 15650

by do_ng 2024. 3. 6.

C++ 코드

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


int N, M;
// N이 1부터 시작하니까 상태배열의 크기를 +1 증가해서 인덱스 1부터 상태체크(해당 숫자 사용 여부)
bool state[9];
int arr[8];

void func(int k) {

	if (k == M) {
		sort(arr, arr + M);
		for (int i = 0; i < M; i++) {
			cout << arr[i] << ' ';
		}
		cout << '\n';
		return;
	}

	int st = 1;
	if (k != 0) st = arr[k - 1] + 1;
	for (int i = st; i <= N; i++) {
		if (!state[i]) {
			arr[k] = i;
			state[i] = 1;
			func(k + 1);
			state[i] = 0;
		}
	}

}


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

	// 1.입력	
	cin >> N >> M;	
	func(0);
	
	return 0;
}

 

int st = 1;
if (k != 0) st = arr[k - 1] + 1;

모든 수열은 중복되지 않으면서 오름차순 정렬을 하도록 해야함

 

 

JAVA 코드

import java.util.Scanner;

public class Main2 {	
	
	static int n,m; 
	static int[] array = new int[10];
 
	public static void func(int k) { 
		if(k == m) {
			for(int i=0;i<k;i++) {
				System.out.print(array[i] + " ");
			}
			System.out.println();
			return;
		}
		
		int start = 1;
		// n=3 일때, start가 3인 경우 (3,1), (3,2) 조합이 생기므로 이 경우에는 for문을 실행하지 않게 처리
		if(k != 0) start = array[k-1]+1; // 값이 동일하면 안되기 때문에 start 지점을 +1 증가
		for(int i=start;i<=n;i++) {			
			array[k] = i;
			func(k+1);	
		}
		
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);	
		n = sc.nextInt();
		m = sc.nextInt();
		func(0);
	}

}

'알고리즘&자료구조 > 백트레킹' 카테고리의 다른 글

백준 15655  (0) 2024.03.11
백준 15654  (0) 2024.03.10
백준 15652  (0) 2024.03.08
백준 15651  (2) 2024.03.07
백준 15649  (0) 2024.03.03