全排列 二 算法

全排列 二 算法

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。

示例 1:

输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

class PermuteUniqueClass
{
	public PermuteUniqueClass()
	{
		//测试
		int[] nums = new int[3] { 1, 1, 3 };
		//int[] nums = new int[] { 1 };

		IList<IList<int>> resultList = PermuteUnique(nums);
		// 输出结果
		foreach(var list in resultList)
		{
			foreach(var v in list)
			{
				Console.Write(v + "   ");
			}
			Console.WriteLine();
		}
	}

	public IList<IList<int>> PermuteUnique(int[] nums)
	{
		IList<IList<int>> resultList = new List<IList<int>>();
		List<int> pathList = new List<int>();
		bool[] used = new bool[nums.Length];
		Dfs(nums, 0, pathList, used, resultList);
		return resultList;
	}

	private void Dfs(int[] nums, int depth, List<int> pathList, bool[] used, IList<IList<int>> resultList)
	{
		if (depth >= nums.Length)
		{
			resultList.Add(new List<int>(pathList));
			return;
		}

		HashSet<int> hash = new HashSet<int>();
		for (int i = 0; i < nums.Length; ++i)
		{
			if (used[i])
			{
				continue;
			}

			if (hash.Contains(nums[i]))
			{
				continue;
			}
			hash.Add(nums[i]);

			pathList.Add(nums[i]);
			used[i] = true;
			Dfs(nums, depth + 1, pathList, used, resultList);
			pathList.RemoveAt(pathList.Count - 1);
			used[i] = false;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值