Fork me on GitHub

47. Permutations II

欢迎fork and star:Nowcoder-Repository-github

47. Permutations II

题目

 Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

解析

首先分析一下与Permutations有何差异。

记当前位置为start,当前排列数组为cur

1、cur[start]与cur[start]值相同的元素交换位置会产生大量重复。

如:1,3,2,1

两个1互换位置之后,后续的所有排列都是重复的。

2、cur[start]与其他相同值的元素多次交换位置会产生大量重复。

如:1,2,3,2

1与两个2互换位置后,后续的所有排列都是重复的。

  • 在全排列中去掉重复的规则——去重的全排列就是从第一个数字起每个数分别与它后面非重复出现的数字交换
  • 参考的方法也有很多是先进行排序,对于同一个值,只交换一次,否则跳过。
class Solution_47 {
public:

	bool IsSwap(vector<int>&nums,int i,int j)
	{
		for (; i < j; i++)
		{
			if (nums[i] == nums[j])
			{
				return false;
			}
		}
		return true;
	}

	void help(int i,vector<int>&nums,vector<vector<int>> &vecs)
	{
		if (i==nums.size())
		{
			vecs.push_back(nums);
			return;
		}
		for (int j = i; j < nums.size(); j++)
		{
			if (IsSwap(nums,i,j))
			{
				swap(nums[i],nums[j]);
				help(i + 1, nums, vecs);
				swap(nums[i],nums[j]);
			}
		}
		return;
	}

	vector<vector<int>> permuteUnique(vector<int>& nums) {
		vector<vector<int>> vecs;
		vector<int> vec;

		if (nums.size()==0)
		{
			return vecs;
		}

		help(0,nums,vecs);

		return vecs;
	}
};

题目来源

posted @ 2018-01-28 12:17  ranjiewen  阅读(231)  评论(0编辑  收藏  举报