1.题目:
给定一个没有重复数字的序列,返回其所有可能的全排列。
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
2.代码:
递归回溯:
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
/*
方法1:从开始数(start),与之后的数字依次交换可以得到所有序列(递归)
(1,2)为交换1,2位:
0 1 2
nums: [1,2,3]
start=0: (0,0)/ (0,1)| (0,2)\
[1,2 3] [2,1,3] [3,2,1]
start=1: (1,1)/ (1,2)| (1,1)/ (1,2)\ (1,1)| \(1,2)
[1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,2,1] [3,1,2]
start=numsSize-1: | | | | | |
赋值 赋值 赋值 赋值 赋值 赋值
注意点:每次start 都要跟自己交换一次,这样就可以保证自身也能加到序列中,上面(0,0),(1,1);
*/
#define MAX 10000
void swap(int i,int j,int *s){
int temp=s[i];
s[i]=s[j];
s[j]=temp;
}
void dfs(int **r,int* nums,int numsSize,int start,int* returnSize){
if(start==numsSize-1){
r[*returnSize]=(int *)malloc(sizeof(int )*numsSize);
memcpy(r[*returnSize],nums,sizeof(int)*numsSize);
(*returnSize)++;
return;
}
for(int i=start;i<numsSize;i++){
swap(start,i,nums);
dfs(r,nums,numsSize,start+1,returnSize);
swap(start,i,nums); //恢复过来
}
}
int** permute(int* nums, int numsSize, int* returnSize) {
int **r=(int **)malloc(sizeof(int *)*MAX);
*returnSize=0;
dfs(r,nums,numsSize,0,returnSize);
return r;
}
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def swap(x,y):
return y,x
def dfs(start,res,nums):
if start == lens-1:
res.append(nums[:])
return
for i in range(start,lens):
nums[i],nums[start] = swap(nums[i],nums[start])
dfs(start+1,res,nums)
nums[i],nums[start] = swap(nums[i],nums[start])
lens = len(nums)
res = []
dfs(0,res,nums)
return res
'''
方法2:used(i) 标记nums[i]是否加入
'''
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def dfs(depth,used,path,res):
if depth==lens:
res.append(path[:])
return
for i in range(lens):
if used[i] == False:
used[i] = True
path.append(nums[i])
dfs(depth+1,used,path,res)
# 恢复
used[i] = False
path.pop()
lens = len(nums)
res = []
path = []
used = [False for _ in range(lens)]
dfs(0,used,path,res)
return res
3.知识点:
DFS回溯