๊ธฐ๋ก๋ฐฉ

BOJ_15656 : N๊ณผ M (7) ๋ณธ๋ฌธ

CodingTest/Java

BOJ_15656 : N๊ณผ M (7)

Soom_1n 2022. 12. 14. 22:03

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

 

15656๋ฒˆ: N๊ณผ M (7)

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

www.acmicpc.net



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

  • n๊ฐœ์˜ ์ˆ˜ ์ค‘์—์„œ 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, StringBuilder sb) {
        if (pick.size() == m) {
            for (int i : pick) {
                sb.append(i + " ");
            }
            sb.append("\n");
            return;
        }

        for (int i = 0; i < n; i++) {
            pick.add(arr[i]);
            dfs(arr, pick, n, m, sb);
            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<>();

        StringBuilder sb = new StringBuilder();

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

        System.out.print(sb.toString());
    }
}

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

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

๐Ÿ”ธ end ๐Ÿ”ธ

  • N๊ณผ M ์‹œ๋ฆฌ์ฆˆ๋Š” ์ต์ˆ™ํ•ด์ ธ์„œ ์žฌ๊ท€ ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฑด ๊ฐ„๋‹จํ–ˆ์ง€๋งŒ, ์ถœ๋ ฅ๋•Œ๋ฌธ์— ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค.
  • StringBuilder๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ•ด๊ฒฐํ–ˆ๋Š”๋ฐ, ๊ผญ ์ตœ๋Œ€๊ฐ’์„ ๋„ฃ์–ด๋ณด๋Š” ๊ฑธ ์Šต๊ด€ํ™” ํ•ด์•ผ๊ฒ ๋‹ค.

728x90

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

BOJ_14501 : ํ‡ด์‚ฌ  (0) 2022.12.17
BOJ_15657 : N๊ณผ M (8)  (0) 2022.12.15
BOJ_15351 : ์ธ์ƒ ์ ์ˆ˜  (0) 2022.12.14
BOJ_15654 : N๊ณผ M (5)  (0) 2022.12.14
BOJ_15652 : N๊ณผ M (4)  (0) 2022.12.11