微软面试题 组合排列算法
2015-04-02 23:25
162 查看
举个例子,比如1,2,3,4这4个数,从中选出任意不同的三个数有几种方案。一共有4种,123,124,134,234;这个就是排列组合算法,现在看看具体算法怎么实现;
假设n个数,从中选择k个不同的数,首先我想到的就是可以充当4个链表,每个链表的数据都是n个数,依次进行访问,确保下一个链表的指针要比前一个链表的指针大,这样才能实现不同,后来发现这样效率很低,于是采用了数组去维护链表指针,可以看做是k个层,根据每层的值来确定指针位置;
代码如下:
#include <stdio.h>
#include <stdlib.h>
int alltest(int s[],int length,int t)
{
int temp[100]={0};
int k=0;
int i=0;
int layer=0;
int res[t];
int a=length-t;
int count=0;
while(temp[0]<=a)
{
while(layer<=t-2)
{
res[layer]=s[temp[layer]];
layer++;
temp[layer]=temp[layer-1]+1;
}
temp[layer]=temp[layer-1]+1;
while(temp[layer]<length)
{
res[layer]=s[temp[layer]];
for(i=0;i<t;i++)
{
printf("%d ",res[i]);
}
count++;
printf("\n");
temp[layer]++;
}
layer=t-1;
while(temp[layer]>=length)
{
// printf("temp=%d\n",temp[layer]);
temp[layer]=0;
layer--;
}
temp[layer]++;
res[layer]=s[temp[layer]];
// k=0;
}
printf("count=%d\n",count);
}
int main()
{
int array[8]={1,2,3,4,5,6,7,8};
alltest(array,8,8);
}
假设n个数,从中选择k个不同的数,首先我想到的就是可以充当4个链表,每个链表的数据都是n个数,依次进行访问,确保下一个链表的指针要比前一个链表的指针大,这样才能实现不同,后来发现这样效率很低,于是采用了数组去维护链表指针,可以看做是k个层,根据每层的值来确定指针位置;
代码如下:
#include <stdio.h>
#include <stdlib.h>
int alltest(int s[],int length,int t)
{
int temp[100]={0};
int k=0;
int i=0;
int layer=0;
int res[t];
int a=length-t;
int count=0;
while(temp[0]<=a)
{
while(layer<=t-2)
{
res[layer]=s[temp[layer]];
layer++;
temp[layer]=temp[layer-1]+1;
}
temp[layer]=temp[layer-1]+1;
while(temp[layer]<length)
{
res[layer]=s[temp[layer]];
for(i=0;i<t;i++)
{
printf("%d ",res[i]);
}
count++;
printf("\n");
temp[layer]++;
}
layer=t-1;
while(temp[layer]>=length)
{
// printf("temp=%d\n",temp[layer]);
temp[layer]=0;
layer--;
}
temp[layer]++;
res[layer]=s[temp[layer]];
// k=0;
}
printf("count=%d\n",count);
}
int main()
{
int array[8]={1,2,3,4,5,6,7,8};
alltest(array,8,8);
}
相关文章推荐
- 输出1到N之间所有相加等于M的数字组合(背包问题)求相加为M的所有组合--微软酷派经典面试题
- 微软面试题(以前从某人blog看到,收藏了)
- 微软Microsoft、谷歌Google、百度、腾讯面试题(三)
- 微软的面试题及答案-经典
- 微软,Google面试题 (1) —— 把二叉排序树转变成排序的双向链表
- 微软,Google面试题 (3) —— 求最大子数组和
- 微软算法面试题(1)
- [置顶] 微软面试题及答案
- 微软面试题
- 微软面试题<三>
- 微软、google、雅虎、百度等各大著名公司的经典面试题!保证搞晕你!!
- 全新整理:微软、Google等公司的面试题及解答、第61-70题
- 微软的22道数据结构算法面试题(含…
- 一个微软面试题--关于位结构体
- 微软100题21题(要求将其中所有的可能组合列出来)
- 微软的面试题及答案-超变态但是很经典
- 微软电话面试题
- 据说是微软的面试题
- 经典面试题(一)附答案 算法+数据结构+代码 微软Microsoft、谷歌Google、百度、腾讯