15652 N과 M(4)

DONGJIN IM·2022년 3월 7일
0

코딩 테스트

목록 보기
3/137

문제 이해

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());
	}
}

결과

  • 틀렸습니다 이유 : N과 M(3) 문제와 너무 비슷하다 생각하여 before라는 인자를 전달하지 않고 마지막에 입력된 data를 Stack에서 확인하는 방식으로 구현하였다. 하지만 이 경우 설정해야 할 예외 처리도 많을 뿐더러 분기도 많아졌기 때문에 분기 처리 과정에서 예상치 못한 틀린 결과가 나왔다고 예상된다. 재귀함수를 이용할 경우 정확도를 위해 Parameter를 최대한 활용하자.
profile
개념부터 확실히!

0개의 댓글

관련 채용 정보