본문 바로가기

알고리즘/재귀

[JAVA] 백준 1182번: 부분수열의 합

문제

N개의 정수로 이루어진 수열이 있을 때, 크기가 양수인 부분수열 중에서 그 수열의 원소를 다 더한 값이 S가 되는 경우의 수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 정수의 개수를 나타내는 N과 정수 S가 주어진다. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) 둘째 줄에 N개의 정수가 빈 칸을 사이에 두고 주어진다. 주어지는 정수의 절댓값은 100,000을 넘지 않는다.

출력

첫째 줄에 합이 S가 되는 부분수열의 개수를 출력한다.

 

import java.util.Scanner;

public class baekjoon1182 {
    static int s;
    static int k;
    static int[] info;
    static int cnt = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        s = sc.nextInt();
        k = sc.nextInt();
        info = new int[s];
        for (int i = 0; i < s; i++) {
            info[i] = sc.nextInt();
        }
        permutation(0, 0, 0);
        System.out.println(cnt);
    }
    static void permutation(int point, int index, int res){
        if (index != 0 && res == k) {
            cnt++;
        }
        if (index == s) {
            return;
        }
        for (int i = point; i < s; i++) {                        
            permutation(i+1, index+1, res+info[i]);            
        }
    }
}

'알고리즘 > 재귀' 카테고리의 다른 글

백준 14501번: 퇴사  (0) 2021.07.31
[JAVA] 백준 16198번: 에너지 모으기  (0) 2021.07.24
[JAVA] 백준 14500번: 테트로미노  (0) 2021.07.22
[JAVA] 백준 6603번: 로또  (0) 2021.07.21