백준 15650 N과 M (2)[Java]

seren-dev·2022년 8월 24일
0

백트래킹

목록 보기
2/8

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

풀이

1부터 N까지 자연수 중에서 중복 없이 M개를 고른 조합을 구하는 문제다.

코드

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+1);
            }
        }
    }

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

    }
}

참고: JAVA 순열, 중복 순열, 조합, 중복 조합 구현

0개의 댓글