c++ - 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?
解决方案
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.
推荐阅读
- python - 如何创建具有 k% True 值的 NumPy 布尔数组?
- sql-server - SQL Server - 从选择语句中的存储过程中获取值
- hadoop - 从 Hadoop MapReduce InputFormat 中传递附加值
- python - 创建对前一天的数据进行分组和转换的列
- java - 如何创建 Spring Batch Service 以读取和处理来自同一临时文件夹的文件(PDF、XML 和 HASH)?
- flutter - Flutter 中的 LTR 和 RTL 问题,易于本地化
- android - React-Native 中的 MapBox-GL 有时无法使用自定义图标标记
- polygon - Solidity 智能合约一次最多可将 1000 个钱包列入白名单
- tensorflow-datasets - 如何处理 .v2 文件?
- django - Nginx,django,docker,拒绝通过本地主机连接