I was stuck in this question Your text to link here... and the editorial doesn't seem to be much helpful to me . However in the discussion section someone explained that this is the dp formula . dp[i][j] = dp[i][j-1]*i + dp[i-1][j]*j-dp[i-1][j-1]*(i-1)*(j-1) i m not able to understand how did he get the third term in the expression and more over i think this needs some correction as i was not able to get the right ans from this.