c++ - 如果我在递归问题中传递 variable++ 和 variable+1 得到不同的 ans,即打印给定数组中 r 元素的所有可能组合
问题描述
#include<bits/stdc++.h>
using namespace std;
int arr[]={1,2,3,4,5};
int r=3;
int rec(int index,int cnt,vector<int> v)
{
if(cnt==r)//if required no is reach
{
cout<<"IN ";
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
return 1;
}
if(index>=5)//crossing the array
{
return 0;
}
int a;
vector<int> temp;
temp=v;
temp.push_back(arr[index]);
a=rec(index+1,cnt+1,temp)+rec(index+1,cnt,v);
return a;
}
int main()
{
vector<int> v;
int cnt=0;
int a=rec(0,cnt,v);
cout<<"a="<<a<<endl;
return 0;
}
```either select the element at the given index and increase the cnt or i dont select the element.In both cases I move forward.The total no of ways in which it can happen is stored in variable a.
(1,2,3) is the same as (2,1,3) or(3,2,1)
I am getting different outputs<br>
CASE-1
a=rec(index+1,cnt++,temp)+rec(index+1,cnt,v);
OUTPUT
进 1 2 3 进 1 2 4 进 1 2 5 进 1 3 4 进 1 3 5 进 1 4 5 进 2 3 4 进 2 3 5 进 2 4 5 进 3 4 5 a=10
CASE-2
a=rec(index+1,cnt+1,temp)+rec(index+1,cnt,v);
OUTPUT
进 1 2 进 1 3 进 1 4 进 1 进 2 3 进 2 4 进 2 进 3 4 进 3 进 a=10
I get different outputs for cnt++ and cnt+1 though both are the same
Why is this happening
解决方案
原因在这里是一样的
看到警告:main.cpp:39:21:警告:对“cnt”的操作可能未定义 [-Wsequence-point]
考虑您的代码如下:
#include <iostream>
#include <vector>
using namespace std;
int arr[] = { 1,2,3,4,5 };
int r = 3;
static int callCounter = 0;
int rec(int index, int cnt, vector<int> v)
{
std::cout << "1+cnt = "<< 1 + cnt << endl;
if (cnt == r)//if required no is reach
{
cout << "IN ";
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
cout << endl;
return 1;
}
if (index >= 5)//crossing the array
{
return 0;
}
int a;
vector<int> temp;
temp = v;
temp.push_back(arr[index]);
//int firstCall = rec(index + 1, cnt, v);
//int secondCall = rec(index + 1, ++cnt, temp);
//a = secondCall + firstCall;
`enter code here`a = rec(index + 1, ++cnt, temp) + rec(index + 1, cnt, v);
//a = rec(index + 1, 1+cnt, temp) + rec(index + 1, cnt, v);
++callCounter;
std::cout << "callCounter " << callCounter <<endl;
return a;
}
int main()
{
vector<int> v;
int cnt = 0;
int a = rec(0, cnt, v);
cout << "a=" << a << endl;
return 0;
}
GCC 9.2 的输出是:
main.cpp: 在函数'int rec(int, int, std::vector)'中:
main.cpp:17:21:警告:不同符号的整数表达式的比较:'int' 和 'std::vector::size_type' {aka 'long unsigned int'} [-Wsign-compare]
17 | for (int i = 0; i < v.size(); i++)
main.cpp:39:21:警告:“cnt”上的操作可能未定义 [-Wsequence-point]
39 | a = rec(index + 1, ++cnt, temp) + rec(index + 1, cnt, v);
推荐阅读
- javascript - 如何在电子表格文件中的所有工作表上运行 Google Apps 脚本?
- sql - 从具有级联下拉列表的 asp.net 详细信息视图更新 Db 表
- javascript - 如何从输入中获取的图像属性中删除边框?
- flutter - 当 GridView 中的容器缩短时 Flutter TextField 不居中
- amazon-web-services - 如何使用 Sagemaker 中经过训练的图像分类模型对通过网页上传的图像进行推理?
- javascript - JavaScript 中不匹配的相同字符串
- python - 如何将图像数据集加载到 TensorFlow 中?
- python - 错误:无法在烧瓶中导入“file_name”
- json - 我将如何在 Dart 中为颤振项目访问此 JSON 数据?
- c++ - Asio 独立 async_connect 连接后不调用回调