题目
- 全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1]
输出:[[0,1],[1,0]]
示例 3:
输入:nums = [1]
输出:[[1]]
提示:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums 中的所有整数 互不相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
memcpy(目标地址,对象地址,大小) 将对象复制到目标地址
这题还是回溯。
第一步 每次固定一个数字在 [0]下标处
第二部 每次固定一个数字在 [1]下标处
然后重复第一步和第二步,然后对其他的元素做交换处理,即可得到所有结果,具体见代码。
代码
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume
* caller * calls free().
*/
void swap(int *nums,int a,int b)
{
int t=nums[a];
nums[a]=nums[b];
nums[b]=t;
}
void prem(int* nums, int numsSize, int* returnSize, int** returnColumnSizes,
int **returnnums,
int cur){
if(cur==numsSize){
returnnums[*returnSize]=(int *)malloc(sizeof(int*)*numsSize);
memcpy(returnnums[*returnSize],nums,sizeof(int)*numsSize);
(*returnColumnSizes)[*returnSize]=numsSize;
*returnSize+=1;
}else{
int i;
for(int i=cur;i<numsSize;i++){
swap(nums,i,cur);
prem(nums,numsSize,returnSize,returnColumnSizes,returnnums,cur+1);
swap(nums,i,cur);
}
}
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes
){
int **returnnums=(int**)malloc(sizeof(int*)*800);
*returnColumnSizes=(int*)malloc(sizeof(int)*800);
*returnSize=0;
prem(nums,numsSize,returnSize,returnColumnSizes,returnnums,0);
return returnnums;
}