곽로그

[백준 15649, 자바 ] N과 M (1) 본문

알고리즘/백준

[백준 15649, 자바 ] N과 M (1)

일도이동 2020. 3. 21. 23:30
반응형

문제

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

 

15649번: N과 M (1)

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

www.acmicpc.net

접근

 

코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class Main {
	public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

	public static void main(String[] args) throws IOException {
		String[] line = br.readLine().split(" ");
		int N = Integer.parseInt(line[0]);
		int M = Integer.parseInt(line[1]);
		
		ArrayList<Integer> candidate = new ArrayList<Integer>();
		NM1(candidate,N,M);
		bw.close();
		

	}
	
	public static void NM1(ArrayList<Integer> candidate, int N, int M) throws IOException {
		if(candidate.size()>=M) {
			for(int i=0;i<candidate.size();i++) {
				bw.write(Integer.toString(candidate.get(i))+" ");
			}
			bw.write("\n");
			
		}
		else {
			for(int num =1 ; num<=N ; num++) {
				if(isPromising(num,candidate)) {
					candidate.add(num);
					NM1(candidate,N,M);
					candidate.remove(candidate.size()-1);
				}
			}
		}
	}
	public static boolean isPromising(int num, ArrayList<Integer>candidate) {
		for(int i=0;i<candidate.size();i++) {
			if(num == candidate.get(i)) {
				return false;
			}
		}
		return true;
	}

}

 

2020.07.27 코드 수정

package may12;

import java.io.BufferedReader;
import java.util.Scanner;

class NM{
    int N;
    int M;
    boolean[] isExist;
    int[] array;

    NM(int N, int M){
        this.N=N;
        this.M=M;
        isExist=new boolean[N+1];
        array=new int[M];
    }

    void getNumArray(int index){
        if(index>=array.length){
            //출력
            for(int num : array){
                System.out.print(num+" ");
            }
            System.out.println();
        }
        else{
            for(int num=1;num<=M;num++){
                if(!isExist[num]){
                    isExist[num]=true;
                    array[index]=num;
                    getNumArray(index+1);
                    isExist[num]=false;
                }
            }
        }
    }
}
public class NM1Demo {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int N= in.nextInt();
        int M= in.nextInt();

        NM nm = new NM(N,M);

        nm.getNumArray(0);
    }

}
반응형
Comments