[백준] 1182번 부분 수열의 합 (구현, java, subset)

728x90
반응형

www.acmicpc.net/problem/1182

 

1182번: 부분수열의 합

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

www.acmicpc.net

subset을 사용해서 처리해줬다.

길이가 1이상이라는 조건이 있다

 

import java.util.Scanner;

public class Main {
	static int n,s;
	static int[] arr;
	static int answer;
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		s=sc.nextInt();
		arr=new int[n];
		for (int i = 0; i < n; i++) {
			arr[i]=sc.nextInt();
		}
		
		subset(0,0,0);
		System.out.println(answer);
		
	}
	private static void subset(int idx,int sum,int cnt) {
		if(idx==n) {
			if(cnt!=0 && sum==s) {
				answer+=1;
			}
			return;
		}
		
		subset(idx+1,sum+arr[idx],cnt+1);
		
		subset(idx+1,sum,cnt);
	}
}
728x90
반응형
TAGS.

Comments