46. Permutations

来源:互联网 发布:联通wcdma 通话 数据 编辑:程序博客网 时间:2024/06/16 02:54

求一个序列的所有排序组合。

题目

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 duplicatespublic 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);            }        }}
原创粉丝点击