15649 N과 M (1)

chi·2023년 10월 30일

백준

목록 보기
8/20
import java.util.Scanner;
import java.util.ArrayList;

public class Main {
	
	
	public static void putting(ArrayList<Integer> list, ArrayList<ArrayList<Integer>> all_list, int n, int m) {
		if (list.size()>=m) {
			all_list.add(new ArrayList<>(list)); // 새로운 ArrayList를 생성하여 추가
			list.remove(list.size() - 1); //pop
			return;
		}
		for(int i=1; i<=n; i++) {
			if(list.contains(i)) continue;
			list.add(i);
			putting(list, all_list, n, m);
			
		}
		if (list.size()!=0) list.remove(list.size() - 1); //pop
		
		
			
	}
	

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt(); //1~n
		int m = scan.nextInt(); //m개 고르기
		ArrayList<Integer> list = new ArrayList<Integer>();
		ArrayList<ArrayList<Integer>> all_list = new ArrayList<ArrayList<Integer>>();
		putting(list, all_list, n, m);
		
		for (int i=0; i<all_list.size(); i++) {
			for (int j=0; j<m; j++) {
				System.out.print(all_list.get(i).get(j)+" ");
			}
			System.out.println();
			
		}
		

		scan.close();
	}
	
}

주의

배열들을 참조형식이라 all_list에 add할 땐 클론을 만들어서 그걸 넣어줘야 됨 오랜만에 해서 까먹었

0개의 댓글