PS/inflearn java coding

간단한 조합 설명.

easy16 2022. 4. 13. 00:36

심플 조합.

nCr = n!/((n-r)!*r!)
5C3 = 5*4*3 / 3! => 5개 중 3개를 중복 되게 뽑은 뒤, 중복되는 경우의 수만큼 나눈다.

nCr = n-1Cr-1 + n-1Cr

ex) 5C3 = 4C2 + 4C3
{1,2,3,4,5} 



말로 설명 하면... 5명중 3명을 뽑는 경우(중복 허용 하지 않음)
5번 기준으로
case 1 : 5가 있는 경우 4C2 (5를 제외한 2개를 뽑는다)
case 2 : 5가 없는 경우 4C3 (3개를 뽑는다)

case 1 + case 2 는 5C3와 같다. 

피보나치와 같이 DFS 및 메모이제이션 활용한다. (2차원 배열)

class Main {

	static int m, n;				

	public int DFS( int n, int r ) {
		
		
		if( comb[n][r] > 0)
			return comb[n][r];
		
		if( r == 0 || n == r )
			return 1;						
		else {
			return comb[n][r]=DFS(n-1, r-1) + DFS(n-1, r);
		}
		 
	}
	static int [][]comb;
	public static void main(String args[]) throws Exception {
		Main M = new Main();
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		m = in.nextInt();
		int MAX =33+1;
		comb= new int[MAX][MAX];
		
		System.out.println( M.DFS(n,  m));
	}

}

ex)
input
33 18
output
1037158320