본문 바로가기

알고리즘/초급1

[JAVA] 백준 15652번: N과 M (4) ( 초급 2-11 )

문제

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

  • 1부터 N까지 자연수 중에서 M개를 고른 수열
  • 같은 수를 여러 번 골라도 된다.
  • 고른 수열은 비내림차순이어야 한다.
    • 길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK-1 ≤ AK를 만족하면, 비내림차순이라고 한다.

입력

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

출력

    • 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다.
    • 수열은 사전 순으로 증가하는 순서로 출력해야 한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class baekjoon10652 {
    private static int n;
    private static int m;
    private static int[] res;
    private static int[] info;
    private static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] string = br.readLine().split(" ");

        n = Integer.parseInt(string[0]);
        m = Integer.parseInt(string[1]);
        info = new int[n];
        res = new int[m];

        for (int i = 0; i < n; i++) {
            info[i] = i + 1;
        }

        combination10652(0, 0);
        System.out.println(sb);
    }

    private static void combination10652(int index, int start) {
        if (index == m) {
            for (int i : res) {
                sb.append(i + " ");
            }
            sb.append("\n");
            return;
        }

        for (int i = start; i < n; i++) {
            res[index] = info[i];
            combination10652(index + 1, i);
        }
    }
}