题目描述
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
算法描述:每个数都做一次开头,利用递归的方法对除第一个数外的所有数两两交换,当index等于数组长度,终止递归并将结果存入链表。
public class Solution {
public IList<IList<int>> Permute(int[] nums)
{
IList<IList<int>> result = new List<IList<int>>();
Perm(result, nums,0);
return result;
}
public static void Perm(IList<IList<int>> result, int[] nums, int index)
{
if (index == nums.Length - 1)
result.Add(new List<int>(nums));
else
{
for (int i = index; i < nums.Length; i++)
{
Swap(nums, index, i);
Perm(result, nums, index + 1);
Swap(nums, index, i);
}
}
}
public static void Swap(int[] nums, int p, int q)
{
int temp = nums[p];nums[p] = nums[q];nums[q] = temp;
}
}
执行结果