给定一个不含重复数字的数组 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 中的所有整数 互不相同
思路:
使用一个数组标记使用过的数字,然后进行搜索
这是我当时学搜索的第一个题目
/**
* 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 dfs(int *nums, int numsSize, int *returnSize, int ** returnColumnSizes,int ** ans, int *book, int *loop, int len){
if(len == numsSize){
ans[*returnSize] = malloc(sizeof(int) * numsSize);
(*returnColumnSizes)[*returnSize] = numsSize;
memmove(ans[*returnSize], loop, numsSize * 4);
(*returnSize)++;
return ;
}
for(int i = 0; i < numsSize; i++){
if(!book[i]){
book[i] = 1;
loop[len] = nums[i];
dfs(nums, numsSize, returnSize, returnColumnSizes, ans, book, loop, len + 1);
book[i] = 0;
}
}
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
int **ans = malloc(sizeof(int *) * 720);
*returnSize = 0;
*returnColumnSizes = malloc(sizeof(int) *720);
int book[10] = {0};
int loop[10] = {0};
dfs(nums, numsSize, returnSize, returnColumnSizes, ans,book, loop, 0);
return ans;
}
|