这个dfs哪里有问题?

#include<bits/stdc++.h>
using namespace std;
long ans=1000,n,b,s,hi[100];
bool dfs(int x,int h)
{
    if(x==n&&h>b)
    {
        ans=min(ans,h-b);
        return 0;
    }
    dfs(x+1,h);
    dfs(x+1,h+hi[x]);
}
int main()
{ 
    freopen("sample.txt", "r", stdin);  
     cin>>n>>b;
     int i;
     for(i=0;i<n;i++)
     cin>>hi[i];
     dfs(0,0);
     cout<<ans;
     return 0;
}

这个算法是求解oj的问题 n个数里找几个数 它们的和比b大而又是满足条件的和里的最小值
在主函数后面的任何cout输出都不显示 为什么啊

阅读 1.9k
1 个回答

你少写一个判断条件,导致无限递归下去了

if (x == n && h>b)
{
    ans = min(ans, h - b);
    return 0;
}
else if (x >= n)
{
    return -1;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题