본문 바로가기
Problem Solving/BOJ

백준- 2798 블랙잭

by 채니_ 2021. 2. 7.

www.acmicpc.net/problem/2798

 

2798번: 블랙잭

첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장

www.acmicpc.net


중복허용X 조합 문제

재귀함수 

기저조건: k==3만큼의길이 and 고른수의합<=주어진M 인경우 Math.max()메소드로 고른수의 합의 최댓값을 구함

유도파트: 카드중에서 3개를 뽑음

 


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static int N,M,res;
	public static void main(String[] args) throws FileNotFoundException {
		System.setIn(new FileInputStream("input/black.txt"));
		Scanner sc = new Scanner(System.in);
		res=0;
		N =sc.nextInt();
		M = sc.nextInt();//제한숫자
		int [] arr = new int [N];
		for (int i = 0; i < N; i++) {
			arr[i]=sc.nextInt();
		}
		//System.out.println(Arrays.toString(arr));
		combination(arr,new int[3],0,0);
		System.out.println(res);
	}
	private static void combination(int[] arr, int[] sel, int idx, int k) {
		if(k==sel.length) {
			int sum=0;
			for (int i = 0; i < sel.length; i++) {
				sum +=sel[i];
			}
			if(sum<=M) {
				res = Math.max(sum, res);
			}
			//System.out.println(res);
			return;
		}
		for (int i = idx; i < N; i++) {
			sel[k]=arr[i];
			combination(arr, sel, i+1, k+1);
		}
		
	}

}

 

'Problem Solving > BOJ' 카테고리의 다른 글

백준- 2941 크로아티아 알파벳  (0) 2021.02.13
백준- 1158 요세푸스 문제  (0) 2021.02.09
백준 - 8320 직사각형을 만드는 방법  (0) 2021.02.07
백준- 15652번 N과M (4)  (0) 2021.02.07
백준- 15651번 N과M (3)  (0) 2021.02.07

댓글