곽로그
[백준 15649, 자바 ] N과 M (1) 본문
반응형
문제
https://www.acmicpc.net/problem/15649
접근
코드
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);
}
}
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준 9663, 자바] N-Queen (0) | 2020.07.28 |
---|---|
[백준 14889,자바] 스타트와 링크 (0) | 2020.03.22 |
[백준 15650, 자바] N과 M (2) (0) | 2020.03.21 |
[백준 1152, 자바] 단어의 개수 (0) | 2020.03.15 |
[백준 2941, 자바] 크로아티아 알파벳 (0) | 2020.03.15 |
Comments