腾讯面试题:根据上排给出的十个数,在其下排填出对应的十个数。

这是一道腾讯面试题目,要求根据上排给出的0到9这十个数字,在下排填出每个数字在上排出现的次数。正确答案为6,2,1,0,0,0,1,0,0,0。解决方案采用深度优先搜索(DFS)策略,通过两个相互递归的函数来实现。" 133208069,19941201,使用CS算法实现SAR成像的Matlab代码实践,"['SAR成像', '压缩感知', 'Matlab编程', '信号处理', '图像重建']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权所有。所有权利保留。

欢迎转载,转载时请注明出处:

http://blog.youkuaiyun.com/xiaofei_it/article/details/17172769

根据上排给出的十个数,在其下排填出对应的十个数,要求下排每个数都是先前上排那十个数在下排出现的次数。

上排的十个数如下:
0,1,2,3,4,5,6,7,8,9

答案是:

6,2,1,0,0,0,1,0,0,0

我在这里使用DFS,并且使用两个函数互相递归。

代码如下:

#include <iostream>
#define MAX 10
using namespace std;

int a[MAX],su;

void output()
{
	for (int i=0;i<MAX;i++)
		cout<<a[i]<<' ';
	cout<<endl;
}

void alloc(int,int,int);
void go(int n)//尝试第n位
{
	if (n==MAX)
	{
		output();
		return;
	}
	int have=0;
	for (int i=0;i<MAX;i++)
		if (a[i]==n) have++;
	int empty=0;
	for (int i=n;i<MAX;i++)
		if (a[i]==-1) empty++;
	int pos;
	for (pos=n+1;pos<MAX;pos++)
		if (a[pos]==-1) break;
	if (a[n]!=-1)
	{
		if (empty<a[n]-have||a[n]<have)
			return;
		alloc(n,a[n]-have,pos);
	}
	else
	{
		for (a[n]=n>have?n:have;a[n]<=have+empty;a[n]++)
		{
			if (a[n]!=n)
				alloc(n,a[n]-have,pos);
			else if (a[n]-1-have>=0)
				alloc(n,a[n]-1-have,pos);
		}
		a[n]=-1;
	}
}

void alloc(int n,int quantity,int pos)//在pos位之后分配quantity个n
{
	if (quantity==0)
	{
		go(n+1);
		return;
	}
	int empty=0;
	for (int i=pos+1;i<MAX;i++)
		if (a[i]==-1) empty++;
	int p;
	for (p=pos+1;p<MAX;p++)
		if (a[p]==-1) break;
	if (pos>=MAX) return;
	a[pos]=n;
	alloc(n,quantity-1,p);
	a[pos]=-1;
	if (empty>=quantity)
		alloc(n,quantity,p);
}

int main()
{
	for (int i=0;i<MAX;i++) a[i]=-1;
	go(0);
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值