Can someone tell me what is the difference in logic between the two solutions?
The first solution is accepted by the CSES
Code 1
#include <bits/stdc++.h>
using namespace std;
#define MOD1 1000000007
#define I int
#define V(x) vector<x>
#define fr(i, s, e) for(int i = s; i < e; i++)
#define fra(i, c) for(auto &i: c)
// CSES Coin Combinations II...
void solve() {
I n, x;
cin >> n >> x;
V(I) c(n);
fra(i, c) cin >> i;
V(V(I)) dp(n, V(I) (x+1, 0));
// state: dp[j][i] = number of ordered ways to produce a sum of money i using the first j coins...
// transition equation: dp[j][i] = dp[j-1][i]+dp[j][i-c[j]]...
fr(j, 0, n)
dp[j][0] = 1; // base cases...
fr(j, 0, n) {
fr(i, 1, x+1) {
if(j > 0) dp[j][i] = dp[j-1][i];
if(i-c[j] >= 0) dp[j][i] = (dp[j][i]+dp[j][i-c[j]])%MOD1;
}
}
cout << dp[n-1][x]; // final subproblem...
// time complexity: O(n*x)*O(1)...
}
int main() {
// setIO("problem_name");
fastio();
I T = 1;
// cin >> T;
while(T--) solve();
}
The second solution is giving TLE
Code 2
#include <bits/stdc++.h>
using namespace std;
#define MOD1 1000000007
#define I int
#define V(x) vector<x>
#define fr(i, s, e) for(int i = s; i < e; i++)
#define fra(i, c) for(auto &i: c)
// CSES Coin Combinations II...
void solve() {
I n, x;
cin >> n >> x;
V(I) c(n);
fra(i, c) cin >> i;
V(V(I)) dp(x+1, V(I) (n, 0));
// state: dp[i][j] = number of ordered ways to produce a sum of money i using the first j coins...
// transition equation: dp[i][j] = dp[i][j-1]+dp[i-c[j]][j]...
fr(j, 0, n)
dp[0][j] = 1; // base cases...
fr(i, 1, x+1) {
fr(j, 0, n) {
if(j > 0) dp[i][j] = dp[i][j-1];
if(i-c[j] >= 0) dp[i][j] = (dp[i][j]+dp[i-c[j]][j])%MOD1;
}
}
cout << dp[x][n-1]; // final subproblem...
// time complexity: O(x*n)*O(1)...
}
int main() {
// setIO("problem_name");
fastio();
I T = 1;
// cin >> T;
while(T--) solve();
}
The only difference in code is the order of nested for loop
Someone please help!