[백준 15650] N과 M (2)

like0·2022년 3월 12일
0

코테준비(JAVA)

목록 보기
10/37

N과 M (1) 문제풀이 링크

문제 설명


N과 M(1) 문제와 달라진 점은 "오름차순"으로 출력을 해야한다는 것이다.

생각 정리

방문하지 않은 경우와 배열에 넣을 때, 이전 인덱스에 있는 값보다 클 경우에만 배열에 값을 넣는다.
배열에 처음 넣을 경우에는, 따로 비교 없이 바로 넣어준다.

완성

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

public class BOJ15650 {
    static int N, M;
    static int arr[];
    static boolean visited[];
    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[N+1];
        visited = new boolean[N+1];
        
        func(0);
    }

    static void func(int current) {
        if(current == M){
            for(int i=0; i<M; i++){
                System.out.print(arr[i] + " ");
            }
            System.out.println();
        }

        for(int i=1; i<=N; i++) {
            if((!visited[i] && current <1) ||  (!visited[i] && arr[current-1] < i) ) { //이 부분에서 오름차순을 위한 조건을 걸어준다.
                visited[i] = true;
                arr[current] = i;
                func(current+1);
                visited[i] = false;
            }
        }
    }
}
profile
배우고 성장하는 개발자가 되기!

0개의 댓글