-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perfect Sum Problem .txt
50 lines (48 loc) · 1.19 KB
/
Perfect Sum Problem .txt
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb=new StringBuffer();
int T=Integer.parseInt(br.readLine());
while(T-->0)
{
int n=Integer.parseInt(br.readLine());
String[] s=br.readLine().split("\\s");
int sum=Integer.parseInt(br.readLine());
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(s[i]);
}
int[][] dp=new int[arr.length+1][sum+1];
sb.append(perfectsum(arr,0,sum,dp)+"\n");
}
System.out.print(sb);
}
public static int perfectsum(int[] arr,int i,int sum,int[][] dp)
{
if(sum==0)
{
return 1;
}
if(i==arr.length)
{
return 0;
}
if(dp[i][sum]!=0)
{
return dp[i][sum];
}
int smallans1=0,smallans2=0;
if(sum-arr[i]>=0)
{
smallans1=perfectsum(arr,i+1,sum-arr[i],dp);
}
smallans2=perfectsum(arr,i+1,sum,dp);
return dp[i][sum]=smallans1+smallans2;
}
}