티스토리 뷰

https://www.acmicpc.net/problem/1182

 

1182번: 부분수열의 합

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

www.acmicpc.net

import java.util.Scanner;

public class Q1182 {

	private static Scanner sc;
	private static int N;
	private static int S;
	private static int[] data;
	private static int answer = 0;
	public static void main(String[] args) {
		solve();
	}
	
	public static void solve() {
		init();
		answer(0 , 0);
		printAnswer();
	}
	
	public static void init() {
		sc = new Scanner(System.in);
		N = sc.nextInt();
		S = sc.nextInt();
		data = new int[N];
		for(int i = 0; i < N;  i++) {
			data[i] = sc.nextInt();
		}
	}
	
	public static void answer(int index, int sum) {
		if(index == N) return;
		if(sum + data[index] == S) answer++;
		
		 answer(index + 1, sum + data[index]);
		 answer(index + 1, sum);
	}
	
	public static void printAnswer() {
		System.out.println(answer);
	}

}

 

-> 재귀를 이용해서 부분수열을 구하는 방식을 취했다.

'알고리즘' 카테고리의 다른 글

실버V. 백준 1479 날짜 계산  (0) 2022.04.04
실버I. 백준2293 동전1  (0) 2021.12.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함