๊ธฐ๋ก๋ฐฉ

BOJ_10974 : ๋ชจ๋“  ์ˆœ์—ด ๋ณธ๋ฌธ

CodingTest/Java

BOJ_10974 : ๋ชจ๋“  ์ˆœ์—ด

Soom_1n 2023. 1. 10. 00:11

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

 

10974๋ฒˆ: ๋ชจ๋“  ์ˆœ์—ด

N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๋ถ€ํ„ฐ N๊นŒ์ง€์˜ ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆœ์—ด์„ ์‚ฌ์ „์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net



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

  • n์ด ์ฃผ์–ด์กŒ์„๋•Œ 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆœ์—ด์„ ์‚ฌ์ „์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

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

import java.util.Scanner;
import java.util.Stack;

public class Main {
    static Stack<Integer> stack;
    private static void dfs(int d, StringBuilder sb) {
        if (stack.size() == d) {
            for (int i :
                    stack) {
                sb.append(i+" ");
            }
            sb.append("\n");
        }
        for (int i = 1; i <= d; i++) {
            if (!stack.contains(i)) {
                stack.push(i);
                dfs(d, sb);
                stack.pop();
            }
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();

        int n = sc.nextInt();
        stack = new Stack<>();

        dfs(n, sb);

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

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

  • ์žฌ๊ท€๋ฌธ์„ ํ†ตํ•ด stack์— 1๋ถ€ํ„ฐ n๊นŒ์ง€ ์ฐจ๋ก€๋Œ€๋กœ ๋„ฃ์–ด ์ˆœ์—ด์„ ์™„์„ฑํ•œ๋‹ค.
  • ์‹œ๊ฐ„์ดˆ๊ณผ๋•Œ๋ฌธ์— StringBuilder์— ๊ฐ’์„ ๋„ฃ๊ณ  ํ•œ ๋ฒˆ์— ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์ฒ˜์Œ์— ์ผ๋ฐ˜ ์ถœ๋ ฅ์œผ๋กœ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์„œ StringBuilder๋กœ ๋ณ€๊ฒฝํ–ˆ๋‹ค.

728x90

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

BOJ_2512 : ์˜ˆ์‚ฐ  (0) 2023.01.11
BOJ_2407 : ์กฐํ•ฉ  (0) 2023.01.10
BOJ_1213 : ํŒฐ๋ฆฐ๋“œ๋กฌ ๋งŒ๋“ค๊ธฐ  (0) 2023.01.10
BOJ_1183 : ์•ฝ์†  (0) 2023.01.09
BOJ_1166 : ์„ ๋ฌผ  (0) 2023.01.06