이유's STUDY/알고리즘 문제풀이

[ 백준 ] 1560번 - N과 m (2) --- java 이용

살아가는 이유_EU 2021. 8. 6. 11:12
728x90
반응형

 

N 과 m 자바를 이용해서 한다~! 

n 과 m (1) 번 문제와 거의 동일하고 우선 오름차순을 해야하기 때문에 정렬 알고리즘인 arr[index] > arr[index-1] 이 되는지 확인을 해주는 로직이 들어간다..! 

 

또한 중복 없이기 때문에 중복을 체크해주기 위해 check[] boolean 배열을 통해서 체크해준다!

 

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

public class Main {
    public static int N, M =0;
    public static StringBuilder sb = new StringBuilder();
    public static boolean check[];

    public static int arr[];
    public static void dfs(int index, int n, int m) {
        // 재귀 탈출 조건
        if(index == m && arr.length == m) {
            for(int ele : arr){
                sb.append(ele+" ");
            }
            sb.append('\n');
            return;
        }

        // 메인 for 문
        for(int i=0; i<n; i++) {
            if(check[i])
                continue;

            check[i] = true;
            arr[index] = i+1;
//            System.out.println(i);
//            System.out.println("index = " + index);
//            System.out.println("arr[index] = " + arr[index]);
            if(index > 0 && arr.length > 1) {
                if(arr[index] < arr[index-1]) {
                    check[i] = false;
                    continue;
                }
            }

            dfs(index+1, n, m);
            check[i] = false;
        }

    }

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

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        //N과 M 배우기.
        StringTokenizer st;
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        // 그다음에 check 와 arr 해준다.
        check = new boolean[N];
        arr = new int[M];

        //dfs 함수 수행
        dfs(0, N, M);
        System.out.println(sb);

    }

}

 

또한 

728x90
반응형