Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
3,152 views
in Algorithms and Problems by | 3,152 views

1 Answer

0 like 0 dislike
Best answer

Lets create our dynamic-programming , dp[i][j] which indicates the number of ways to divide an array of size 'i' into 'j' distinct parts .. 

What can be the recurrence relation ? 

dp[i][j] = (dp[i-1][j-1]  + dp[i-2][j-1] + ......... and so on..till dp[j-1][j-1])

 

Basically , to calculate the best answer for index 'i' ,  we select a block of size '1' at index 'i' and calculate the number of ways possible to make j-1 parts as the last block will make total 'j' parts.. , which will be dp[i-1][j-1].  

Similarly, we try to make last block of size '2' , then size '3' , then size '4' , then size '5' , ... and so on.... 

So it adds up ..... //RAM__rAM!!!

Code C++ : 

#include <bits/stdc++.h>
using namespace std ;
int dp[100+5][5+10];
int main()
{
    int n,k; 
    cin>>n>>k; 
    int j = 1; 
    while(j<=n)
    {
        dp[j][1] = 1 ; 
        j++;
    }
    int p = 2 ; 
    while(p<=k)
    {
        //dp[i][p] ==== dp[i-1][p-1] + dp[i-2][p-1] + dp[0][p-1]..........
        int i = p;
        while(i<=n)
        {
            
            int j = i-1;
            int sum = 0 ; 
            while(j>=1)
            {
                sum = sum + dp[j][p-1];
                j--;
            }
            dp[i][p] = sum  ; 
            i++;
        }
        p++;
    }
    cout<<dp[n][k] ; 
    return 0 ; 
}
by Expert (107,880 points)

Get best answers to any doubt/query/question related to programming , jobs, gate, internships and tech-companies. Feel free to ask a question and you will receive the best advice/suggestion related to anything you ask about software-engineering , development and programming problems .