您的位置:首页 > 其它

《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结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: