首页 > 解决方案 > How does change in Passing parameters changes the output of the Code?

问题描述

When I pass only Sum as Parameter in My coin Exchange Problem to find no of ways to find the amount Sum.. Example if the coins are {2,3,5} and the desired sum is 9 i get correct output as 8. This code :



#include <bits/stdc++.h>

using namespace std;

int n, sum, a[105];

int fun(int sum) {
    int S = 0;
    if(sum == 0) return 1;
    
    if(sum < 0) return 0;
    
    for(int i=1;i<=n;i++) {
        
        S += fun(sum - a[i]);
    }
    
    
    return S;
}

int main()
{
    cin >> n;
    cin >> sum;
    for(int i=1;i<=n;i++ ) {
        cin >> a[i];
    }
    cout << fun(sum);
    

    return 0;
}

But when I also give Current Index as a parameter it gives me output as 3 which is wrong.

This code :



#include <bits/stdc++.h>

using namespace std;

int n, sum, a[105];

int fun(int sum, int idx) {
    int S = 0;
    if(sum == 0) return 1;
    if(idx > n) return 0;
    if(sum < 0) return 0;
    
    for(int i=idx;i<=n;i++) {
        
        S += fun(sum - a[i], i);
    }
    
    
    return S;
}

int main()
{
    cin >> n;
    cin >> sum;
    for(int i=1;i<=n;i++ ) {
        cin >> a[i];
    }
    cout << fun(sum,1);
    

    return 0;
}

But WHY?? Is my parameter passing in this case is wrong?

标签: c++

解决方案


You don't have the same result between your 2 solutions because in the first, at each "function call", you will iterate from 1 to N and in your second solution, you will iterate from Index to N. So the number of loop will be different.


推荐阅读