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

seren-dev·2022년 8월 24일
0

백트래킹

목록 보기
4/8

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

풀이

  • 1부터 N까지 자연수 중에서 중복을 허용하여 M개를 고른 수열을 모두 출력한다.
  • 고른 수열은 비내림차순이어야 한다.
  • 길이가 K인 수열 A가 A1 ≤ A2 ≤ ... ≤ AK-1 ≤ AK를 만족하면, 비내림차순이라고 한다.
    -> 중복 조합

코드

import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Main {

    static int n, m;
    static int[] comb;
    static StringBuilder sb = new StringBuilder();

    static public void combination(int L, int start) {
        if (L == m) {
            for (int i : comb)
                sb.append(i + " ");
            sb.append("\n");
        }
        else {
            for (int i = start; i <= n; i++) {
                comb[L] = i;
                combination(L+1, i);
            }
        }
    }

    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());

        comb = new int[m];

        combination(0, 1);
        System.out.println(sb);
    }
}

조합과 중복조합의 차이는 재귀 시작 지점의 차이다. 조합은 중복을 허용하지 않기 때문에 combination(L+1, i+1)을 호출하지만, 중복 조합은 combination(L+1, i)을 호출한다.

0개의 댓글