首页 > 解决方案 > 如果我在递归问题中传递 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

标签: c++recursion

解决方案


原因在这里是一样的

看到警告: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);


推荐阅读