《leetCode》:Permutations
2015-11-08 21:08
155 查看
题目
Given a collection of numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
思路
思路与《剑指Offer》上面的这个题目的思路一样:http://blog.csdn.net/u010412719/article/details/48980787/** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ /* 求一个数组的全排列 利用递归来做, */ int **result; int index_my=0; void swap(int *a,int *b){ int temp=*a; *a=*b; *b=temp; } int **my_premute(int *nums,int k,int length){ if(nums==NULL||length<1){ return NULL; } if(k==length){//其中的一种情况,保存 result[index_my]=(int *)malloc(length*sizeof(int)); if(result[index_my]==NULL){ exit(EXIT_FAILURE); } for(int i=0;i<length;i++){ result[index_my][i]=nums[i]; } index_my++; } else{ for(int i=k;i<length;i++){ swap(&nums[i],&nums[k]);//都与第k个元素进行交换,然后进行下一轮的递归。 my_premute(nums,k+1,length); swap(&nums[i],&nums[k]);//还原 } } } int** permute(int* nums, int numsSize, int* returnSize) { if(nums==NULL||numsSize<1){ return NULL; } int num=1; for(int i=1;i<=numsSize;i++){ num*=i; } index_my=0; result=(int **)malloc(num*sizeof(int *)); if(result==NULL){ printf("malloc fail"); exit(EXIT_FAILURE); } my_premute(nums,0,numsSize); *returnSize=index_my; return result; }
测试代码如下:
int main(void){ int k; while(scanf("%d",&k)!=EOF){ int *arr=(int *)malloc(k*sizeof(int)); if(arr==NULL){ exit(EXIT_FAILURE); } for(int i=0;i<k;i++){ scanf("%d",arr+i); } int returnSize=0; int **temp=permute(arr,k,&returnSize); for(int i=0;i<returnSize;i++){ for(int j=0;j<k;j++){ printf("%d ",temp[i][j]); } printf("\n"); } printf("\n"); } }
遇到一个比较奇葩的问题也: ‘index’ redeclared as different kind of symbol
我找了半天,没有找到index被我重复定义了。但是就是报错。无奈之下只能换一下这个名字了,将index换成index_my,再运行就OK了。
想了下,产生这个问题的原因应该是,leetCode后台的测试代码中,也用到了这个变量,而我这里的index是声明的是全局变量,因此产生了冲突。
AC结果如下:
相关文章推荐
- 一个英语学渣是如何通过英语六级的
- 数组中出现次数超过一半的数字
- hdu1026 Ignatius and the Princess I
- 文件操作
- C语言实现链表之单向链表(五)头结点前插入结点
- Android 系统信息获取(CPU,RAM,ROM,Battery,SD-card,版本等)
- LESS 原理及使用方式
- C语言实现链表之单向链表(四)清空链表
- NOIP2015酱油记
- POJ3292Semi-prime H-numbers(筛选法)
- array [].Getlength与array[].length
- HDU 4460 SPFA
- Linux /Dev 常见特殊设备介绍与应用
- 一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10
- 多核mips异常分析(1)
- UINavigationController 总结
- zoj3652Maze(广搜+优先队列+移位+与,或运算)
- HDU 4462 枚举
- 【转】ubuntu的防火墙安装、开启和关闭
- svn不支持中文路径问题的解决