《leetCode》:Permutations
来源:互联网 发布:像素绘画软件 编辑:程序博客网 时间:2024/06/08 20:03
题目
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结果如下:
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- 【LeetCode】Permutations
- C语言实现链表之单向链表(五)头结点前插入结点
- 数组中出现次数超过一半的数字
- 一个英语学渣是如何通过英语六级的
- 编程之美-饮料供货方法整理
- Exploring ES6(Leanpub ‘15)笔记(仅目录提纲)
- 《leetCode》:Permutations
- hdu1026 Ignatius and the Princess I(bfs+路径)
- C语言实现链表之单向链表(六)删除头结点
- U盘刻录GSMS软件系统ISO文件教程
- 【DP】 HDU 3229 Jinyuetuan Puzzle
- 第八周--数据结构--字符串加密
- 重叠I/O详解
- zabbix设置sendmail发送邮件
- C语言实现链表之单向链表(七)尾结点后插入结点