๊ธฐ๋ก๋ฐฉ

BOJ_15654 : N๊ณผ M (5) ๋ณธ๋ฌธ

CodingTest/Java

BOJ_15654 : N๊ณผ M (5)

Soom_1n 2022. 12. 14. 01:58

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

 

15654๋ฒˆ: N๊ณผ M (5)

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

www.acmicpc.net



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

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

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

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

public class Main {
    static ArrayList<Integer> arr, pick;
    static int n, m;

    private static void dfs() {
        if (pick.size() == m) {
            for (int i : pick) {
                System.out.print(arr.get(i) + " ");
            }
            System.out.println("");
        }
        for (int i = 0; i < n; i++) {
            if (!pick.contains(i)) {
                pick.add(i);
                dfs();
                pick.remove(pick.size()-1);
            }
        }
    }

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

        arr = new ArrayList<>();
        pick = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            arr.add(sc.nextInt());
        }

        Collections.sort(arr);

        dfs();
    }
}

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

  • ์žฌ๊ท€๋ฉ”์†Œ๋“œ dfs๋กœ ์ˆ˜๋ฅผ ์„ ํƒํ•ด์„œ ArrayList์— ์ €์žฅํ•œ๋‹ค.
    • ArrayList์— ์ด๋ฏธ ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.
  • ArrayList์— ์ €์žฅํ•œ ์ˆ˜๊ฐ€ m๊ฐœ๊ฐ€ ๋˜๋ฉด ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์Šคํƒ์œผ๋กœ ๊ตฌํ˜„ํ•ด๋ณด๋ ค๊ณ  ํ–ˆ์ง€๋งŒ, ๋„ˆ๋ฌด ๋ณต์žกํ•ด์ง€๋Š” ๊ฒƒ ๊ฐ™์•„ ์žฌ๊ท€ ๋ฉ”์†Œ๋“œ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.

728x90

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

BOJ_15656 : N๊ณผ M (7)  (0) 2022.12.14
BOJ_15351 : ์ธ์ƒ ์ ์ˆ˜  (0) 2022.12.14
BOJ_15652 : N๊ณผ M (4)  (0) 2022.12.11
BOJ_15651 : N๊ณผ M (3)  (0) 2022.12.10
BOJ_15650 : N๊ณผ M (2)  (0) 2022.12.09