Leetcode 47. Permutations II

class Solution {
public:
	bool repeat(vector<int>& nums, int begin,int j) 
	{
		for (int i = begin; i < j; i++) 
		{
			if (nums[i] == nums[j]) 
			{
				return true;
			}
		}
		return false;
	}
	void fun(vector<vector<int>> &ans, vector<int>& nums, vector<int> &temp,int index)
	{
		if (index == nums.size()-1) 
		{
			temp.push_back(nums[index]);
			ans.push_back(temp);
			temp.pop_back();
			return;
		}
		else 
		{
			for (int i = index; i < nums.size(); i++) 
			{
				if (i==index||repeat(nums,index,i)==false) 
				{
					temp.push_back(nums[i]);
					swap(nums[i], nums[index]);
					fun(ans, nums, temp, index + 1);
					temp.pop_back();
					swap(nums[i], nums[index]);
				}
			}
		}
	}
	vector<vector<int>> permuteUnique(vector<int>& nums)
	{
		vector<vector<int>> ans;
		vector<int> temp;
		fun(ans, nums,temp, 0);
		return ans;

	}
};
解法:还是回溯法,和上一题基本一样,多了一点,要判断当前点和之前的有没有重复。

47. Permutations II

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

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页