🐣 알고리즘 삐약

85 삐약 : 백준 15651| N과 M (3) [바킹독| 백트래킹 |JAVA]

우주수첩 2024. 8. 13. 22:25
728x90

 

시간 초과

package BKD_0x0C_BackTracking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class BOJ_15651 {
    static int N;
    static int M;
    static int[] arr;

    static void dfs(int depth){
        if(depth==M){
            for(int val : arr){
                System.out.print(val + " ");
            }
            System.out.println();
            return;

        }
        for(int i=0;i<N;i++){
            if(depth<M){
                arr[depth] =i+1;
                dfs(depth+1);

            }
        }
        return;

    }
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        arr = new int[M];
        dfs(0);
    }
}

 

 

 

 

수정

package BKD_0x0C_BackTracking;

import java.io.*;
import java.util.StringTokenizer;

public class BOJ_15651 {
    static int N;
    static int M;
    static int[] arr;
    static StringBuilder sb = new StringBuilder();

    static void dfs(int depth){
        if(depth==M){
            for(int val : arr){
                sb.append(val).append(' ');
            }
            sb.append('\n');
            return;

        }
        for(int i=0;i<N;i++){
            if(depth<M){
                arr[depth] =i+1;
                dfs(depth+1);

            }
        }
        return;

    }
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        arr = new int[M];
        dfs(0);
        System.out.println(sb);
    }
}

 

 

아자뵤

728x90