[Java] 백준 15651번

박세윤·2022년 5월 10일
0

BaekJoon Online Judge

목록 보기
45/95
post-thumbnail

백준 15651번

N과 M (3)

문제

자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.

1부터 N까지 자연수 중에서 M개를 고른 수열
같은 수를 여러 번 골라도 된다.

입력

첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 7)

출력

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

수열은 사전 순으로 증가하는 순서로 출력해야 한다.

예제

알고리즘 분류

  • 백트래킹

코드

import java.util.*;
import java.io.*;

public class Main {	
	public static int arr[];
	public static int N, M;
	public static StringBuilder sb = new StringBuilder();
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		
		arr = new int[M];
		
		DFS(0);
		
		System.out.println(sb);
	}
	
	public static void DFS(int depth) {
		if(depth == M) {
			for(int i=0; i<M; i++)
				sb.append(arr[i]).append(' ');
			
			sb.append('\n');
			
			return;
		}
		
		for(int i=1; i<=N; i++) {
			arr[depth] = i;
			DFS(depth + 1);
		}
	}
}

풀이

DFS로 문제를 해결했다.
가장 처음으로 탐색할 노드는 모든게 1인 11111... 일 것이고
그 다음 탐색 노드는 111... 112 일 것이다.

중복이 허용되기 때문에 다른 특별한 장치나 조건 없이, 처음부터 끝노드 까지 반복하면 된다.

profile
개발 공부!

0개의 댓글