N과 M(3) 문제에서 '비내림차순'이라는 조건이 포함된 문제이다.
원래 N과 M(3) 문제에서 for문에서 1 ~ N까지의 data를 Stack에 집어 넣었지만, 비내림차순이라는 조건이 만족되어야 하므로 이전에 Stack에 넣었던 Data를 다음 재귀함수에 전달하여 활용하는 방식으로 구현해야겠다고 생각했다.
import java.util.*;
public class Main {
static StringBuilder sb = new StringBuilder();
static int N;
static void rec_fun(int length, Stack<Integer> tmp, int before) {
// before : 이전 재귀함수 때 Stack에 넣었던 data
if(length==0) {
String answer = tmp.toString();
sb.append(answer.substring(1,answer.length()-1)
.replaceAll(",","")+"\n");
return;
}
for(int i = before;i<=N;i++) {
//비내림차순이므로 before부터 for문을 시작해야 한다.
tmp.push(i);
rec_fun(length-1, tmp, i);
tmp.pop();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
int M = sc.nextInt();
rec_fun(M, new Stack<Integer>(), 1);
System.out.println(sb.toString());
}
}