Given three integers n
, k
and d
, how many ways can n
be represented as sum of positive integers i<=k
, such that d
occurs at least once in the sum. It is guarenteed that 0<d<=k
. My approach was a recursive one;
#include <stdio.h>
#include <stdlib.h>
int n,k,d,ans=0;
void solve(int totw,int flag)//totw is the total sum till now, and flag is to keep track of the number of d's in the sum.
{
if(totw>n)
return;
if(totw==n && flag>0)//flag>0--->at least 1 d
{
ans = (ans+1)%1000000007;//answer is expected modulo 10^9+7
return;
}
int i=1,h=k;
if(h>n-totw)
h=n-totw;
while(i<=h)
{
if(i==d)
flag++;
solve(totw+i,flag);
i++;
}
}
int main()
{
scanf("%d %d %d",&n,&k,&d);
solve(0,0);
printf("%d",ans);
}
Input:
3 3 2
Output:
2
But the judge shows Time Limit Exceeded
. Is there any more efficient algorithm to proceed with in this case? 0<n,k<=100
PS:I was just wondering whether there is any combinatoric argument that can solve this question without recursion
or iteration
. And yes....order of sums matter.