๊ธฐ๋ก๋ฐฉ

BOJ_15657 : N๊ณผ M (8) ๋ณธ๋ฌธ

CodingTest/Java

BOJ_15657 : N๊ณผ M (8)

Soom_1n 2022. 12. 15. 19:55

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

15657๋ฒˆ: N๊ณผ M (8)

N๊ฐœ์˜ ์ž์—ฐ์ˆ˜์™€ ์ž์—ฐ์ˆ˜ M์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์•„๋ž˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๊ธธ์ด๊ฐ€ M์ธ ์ˆ˜์—ด์„ ๋ชจ๋‘ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. N๊ฐœ์˜ ์ž์—ฐ์ˆ˜๋Š” ๋ชจ๋‘ ๋‹ค๋ฅธ ์ˆ˜์ด๋‹ค. N๊ฐœ์˜ ์ž์—ฐ์ˆ˜ ์ค‘์—์„œ M๊ฐœ๋ฅผ ๊ณ ๋ฅธ ์ˆ˜์—ด

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • n๊ฐœ์˜ ์ˆ˜ ์ค‘์—์„œ m๊ฐœ๋ฅผ ๋ฝ‘๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
  • ์ˆ˜์—ด์€ ์ค‘๋ณต๋˜๋ฉด ์•ˆ๋˜๋ฉฐ ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ, ์‚ฌ์ „์ˆœ ์ฆ๊ฐ€์ˆœ์„œ์ด๋‹ค.
  • ์žฌ๊ท€๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ m๊ฐœ์˜ ์ˆ˜๋ฅผ ๊ณ ๋ฅธ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    private static void dfs(int[] arr, ArrayList<Integer> pick, int n, int m, int i){
        if (pick.size() == m) {
            for (int j : pick) {
                System.out.print(j + " ");
            }
            System.out.println("");
            return;
        }

        for (int j = i; j < n; j++) {
            pick.add(arr[j]);
            dfs(arr, pick, n, m, j);
            pick.remove(pick.size()-1);
        }

    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

        int[] arr = new int[n];

        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        Arrays.sort(arr);
        ArrayList<Integer> pick = new ArrayList<>();

        dfs(arr, pick, n, m, 0);

    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • ์žฌ๊ท€๋ฉ”์†Œ๋“œ๋กœ ์ˆ˜๋ฅผ ๊ณจ๋ผ ArrayList์— ์ €์žฅํ•˜๊ณ  m๊ฐœ๊ฐ€ ๋˜๋ฉด ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • N๊ณผ M ์‹œ๋ฆฌ์ฆˆ์—์„œ ์ด์ „์— ๋‚˜์˜จ๊ฑฐ๋ž‘ ์™„์ „ํžˆ ๊ฐ™์€ ๊ฒƒ ๊ฐ™์€๋ฐ ์™œ 8๋ฒˆ์ธ์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค.

728x90

'CodingTest > Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ_1904 : 01ํƒ€์ผ  (0) 2022.12.18
BOJ_14501 : ํ‡ด์‚ฌ  (0) 2022.12.17
BOJ_15656 : N๊ณผ M (7)  (0) 2022.12.14
BOJ_15351 : ์ธ์ƒ ์ ์ˆ˜  (0) 2022.12.14
BOJ_15654 : N๊ณผ M (5)  (0) 2022.12.14