-
/* <N과 M(1)> */ import java.util.*; class Main { public static int[] arr; //값을 넣을 배열 public static boolean[] visit; //방문했는지 체크하기 위한 배열 public static void main(String args[]) { Scanner sc = new Scanner(System.in); //사용자로부터 숫자를 입력받기 위한 Scanner int N = sc.nextInt(); //N을 입력받는다. => 3입력 int M = sc.nextInt(); //M을 입력받는다. => 2입력 arr = new int[M]; //배열 크기를 할당 => 2만큼 크기를 할당 visit = new boolean[N]; //배열의 크기를 할당 => 3만큼 크기를 할당 dfs(N, M, 0); //dfs함수 호출 => 인자로 3, 2, 0을 넣는다. 0을 넣는 이유는 처음 시작할때 깊이가 0부터 시작하기 때문이다. } //탐색하기 위한 dfs함수 => 파라미터로 3개의 값을 받는다. public static void dfs(int N, int M, int depth){ if(depth == M){ //깊이가 M이 될 경우 => 즉 현재의 경우에서 depth가 2가 될 경우를 의미한다. for(int val : arr){ //배열에 있는 원소를 화면에 출력하기 위한 반복문 System.out.print(val + " "); //배열의 0번째 부터 arr.length - 1까지 원소를 화면에 출력한다. } System.out.println(); //줄바꿈 return; //리턴 } for(int i = 0; i < N; i++){ // 0 ~ 2까지 반복문을 수행 if(!visit[i]){ //visit의 i번째 원소가 false일 경우 조건문 내부를 수행한다. visit[i] = true; //해당 i번째 원소를 true로 변경시키고, arr[depth] = i + 1; //arr[0] = 1을 대입한다. dfs(N, M, depth + 1); //dfs(3, 2, 1)호출 visit[i] = false; } } } }
import java.util.Scanner; /** * @author Kojihun * (백준 15649) N과 M(2) */ public class Main { public static int[] arr; public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); arr = new int[M]; dfs(N, M, 1, 0); } public static void dfs(int N, int M, int at, int depth){ if(depth == M){ for(int val : arr){ System.out.print(val+" "); } System.out.println(); return; } for(int i = at; i <= N; i++){ arr[depth] = i; dfs(N, M, i + 1, depth + 1); } } }