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

原文链接:http://blog.csdn.net/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;  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值