๊ธฐ๋ก๋ฐฉ

BOJ_15351 : ์ธ์ƒ ์ ์ˆ˜ ๋ณธ๋ฌธ

CodingTest/Java

BOJ_15351 : ์ธ์ƒ ์ ์ˆ˜

Soom_1n 2022. 12. 14. 03:20

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

 

15655๋ฒˆ: N๊ณผ M (6)

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(ArrayList<Integer> pick, int[] arr, int n, int m, int k) {
        if (pick.size() == m) {
            for (int i : pick) {
                System.out.print(i + " ");
            }
            System.out.println();
            return;
        }
        for (int i = k; i < n; i++) {
            if (!pick.contains(arr[i])){
                pick.add(arr[i]);
                dfs(pick, arr, n, m, i);
                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);

        dfs(new ArrayList<>(), arr, n, m, 0);
    }
}

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

  • ์žฌ๊ท€ ๋ฉ”์†Œ๋“œ dfs๋กœ ์ˆ˜๋ฅผ ์„ ํƒํ•ด ArrayList์— ๋‹ด๊ณ  m๊ฐœ๊ฐ€๋˜๋ฉด ์ถœ๋ ฅํ•œ๋‹ค.
  • ์ˆœ์—ด์˜ ์ค‘๋ณต์„ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด ์–ด๋Š ์ธ๋ฑ์Šค๊นŒ์ง€ ArrayList์— ๋‹ด์•˜๋Š”์ง€ k์— ๊ธฐ๋กํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์ค‘๋ณต์„ ํ”ผํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์„ธํŠธ์— ๋‚จ์•„์•ผํ•˜๋Š”์ง€ ์ƒ๊ฐํ•˜๋‹ค ๋ฌด์กฐ๊ฑด ์˜ค๋ฆ„์ฐจ์ˆœ์ด๋ผ๋Š” ๊ฒƒ์„ ์ƒ๊ฐํ•˜๊ณ  k๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

728x90

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

BOJ_15657 : N๊ณผ M (8)  (0) 2022.12.15
BOJ_15656 : N๊ณผ M (7)  (0) 2022.12.14
BOJ_15654 : N๊ณผ M (5)  (0) 2022.12.14
BOJ_15652 : N๊ณผ M (4)  (0) 2022.12.11
BOJ_15651 : N๊ณผ M (3)  (0) 2022.12.10