求一个序列的所有排序组合。
题目
Given a collection of distinct 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],
[3,2,1]
]
思路
深度搜索
递归实现
代码
//assert: distinct elements, no duplicates
public class Solution {
private IList<IList<int>> result = new List<IList<int>>();
public IList<IList<int>> Permute(int[] nums)
{
Array.Sort(nums);
dfs(new List<int>(), nums);
return result;
}
private void dfs(IList<int> tmp, int[] nums)
{
if (tmp.Count == nums.Length)
{
result.Add(new List<int>(tmp));
return;
}
for (int i = 0; i < nums.Length; i++)
{
if (tmp.Contains(nums[i]))
continue;
tmp.Add(nums[i]);
dfs(tmp, nums);
tmp.RemoveAt(tmp.Count - 1);
}
}
}