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

来源:互联网 发布:java打印一个倒三角形 编辑:程序博客网 时间:2024/05/22 15:19

原文链接: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;  }