study/백준

[백준문제풀이] 15649 N과M

SHplusR 2023. 11. 3. 23:26

 

접근법 : 

**1) 어떻게 풀 것인가?**

문제는 쉽게 이해간다.

1부터 n까지의 수를 M개씩 중복순열로 출력하면 된다.

 

**2) 시간복잡도**

O(n!)인데 n의 최대는 8이므로 시간안에 충분히 가능하다

 

**3) 공간복잡도**

512mb

 

**4) 풀면서 놓쳤던점**

딱히 없다

 

**5) 이 문제를 통해 얻어갈 것**

백트래킹에 대한 이해!

 

import java.io.*;

public class Main {

    static int n,m;
    static int[] ints;
    static boolean[] visit;
    static StringBuilder sb = new StringBuilder();

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

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strings = br.readLine().split(" ");
        n = Integer.parseInt(strings[0]);
        m = Integer.parseInt(strings[1]);
        ints = new int[n+1];
        visit = new boolean[n+1];

        dfs(0);
        System.out.println(sb);

    }

    public static void dfs(int cnt) {
        if (cnt == m) {
            for(int i=1;i<=m;i++){
                sb.append(ints[i]+" ");
            }
            sb.append('\n');
            return;
        }

        for (int i =1; i <=n; i++) {
            if (!visit[i]) {
                visit[i] = true;
                ints[cnt+1] = i;
                dfs(cnt + 1);
                visit[i] = false;
            }
        }
    }
}