21.09.06 기록

최대 1 분 소요

백준 알고리즘 15652 풀이

🎆나의 풀이(메모리 14.9MB, 시간 164ms로 통과)

-지난 문제인 #15650를 응용하여 풀이했다.
-계속 백트래킹 문제를 풀다보니 로직에 좀 익숙해졌다. 하지만, 역시 어려워서 백트래킹에서 벗어나고 싶다…(백트래킹 그만..ㅠㅠ)
-이번 문제의 해설도 크게 추가된 내용이 없어서 생략했다.

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

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

    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());
        nums = new int[M];

        dfs(0, 1);
        System.out.println(sb);
    }

    public static void dfs(int depth, int start) {
        if(depth == M) {
            for(int i = 0; i < M; i++) {
                sb.append(nums[i]).append(" ");
            }
            sb.append("\n");
            return;
        }

        for(int i = start; i <= N; i++) {
            nums[depth] = i;
            dfs(depth+1, i);
        }
    }


카테고리:

업데이트: