본문 바로가기
백준

백준 백트래킹 - 15650번 : N과 M (2)

by 맴썰 2022. 2. 11.

 

https://www.acmicpc.net/problem/15650

 

15650번: N과 M (2)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net


import java.io.*;
import java.util.*;
public class Main {
	
	public static void main(String[] args) throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		
		StringTokenizer st;
		st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());
		int[] a = new int[n];
		for(int i=0; i<n; i++){
		   a[i] = i+1;
		}
		br.close();
		for(int i=0; i<n; i++) {
			int[] copy = a.clone();
			dfs(copy,"",m,i);
		}
    }
	public static void dfs(int[] a, String target, int m,int idx){
		if(a[idx]==0) return;
		target = target.concat(Integer.toString(a[idx]));
		
		if(target.length()==m) {
			print(target);
			return;
		}
		for(int i=0; i<a.length; i++) {
			if(a[i]==0||a[i]<a[idx]) continue;
			else {
				a[idx] = 0;
				int[] copy = a.clone();
				dfs(copy,target,m,i);
				
			}
		}
	}
	 static void print(String a) {
		for(int i=0; i<a.length(); i++) {
			System.out.print(a.charAt(i)+ " ");
		}
		System.out.println();
	}
}