You are not logged in. Please login at www.codechef.com to post your questions!

×

Why my recurrence is getting wrong?

I was solving this question on hackerearth - https://www.hackerearth.com/problem/algorithm/supernatural-squad-2/description/

I came through the recurrence relation (doesn't works correctly

if(dp[N][K] != -1)
    return dp[N][K];
if(K == 0)
    return 0;
if(K > N)
    return 0;
if(N == K)
    return 1;
else
{
    dp[N-K][K] = solve(N-K,K);   // Kth number is selected,problem reduced to subproblem with new sum as N - K
    dp[N][K - 1] = solve(N,K - 1);  // Kth number isn't selected,we need to explore upto (K - 1) now
    dp[N][K] = dp[N-K][K] + dp[N][K - 1];
    return dp[N][K];
}

instead of(works fine)

if(dp[N][K] != -1)
    return dp[N][K];
if(K == 0)
    return 0;
if(K > N)
    return 0;
if(N == K)
    return 1;
else
{
    dp[N-K][K] = solve(N-K,K);
    dp[N][K + 1] = solve(N,K + 1);
    dp[N][K] = dp[N-K][K] + dp[N][K + 1];
    return dp[N][K];
}

Whats the difference between 2 approaches for solving the above problem?

asked 23 Dec '15, 16:05

sandeep9's gravatar image

3★sandeep9
4782827
accept rate: 4%

edited 23 Dec '15, 16:07

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×2,168
×887

question asked: 23 Dec '15, 16:05

question was seen: 480 times

last updated: 23 Dec '15, 16:07