leetcode 46. Permutations

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], and [3,2,1].



class Solution {
public:
	vector<vector<int>> permute(vector<int>& nums) {
		vector<vector<int>>re;
		if (nums.empty())
			return re;
		if (nums.size() == 1)
		{
			re.push_back(nums);
			return re;
		}
		map<vector<int>, vector<int>>candi;
		vector<int>aa; candi[aa] = nums;
		int k = 0;
		while (true)
		{
			map<vector<int>, vector<int>>newcandi;
			for (map<vector<int>, vector<int>>::iterator it = candi.begin(); it != candi.end(); it++)
			{
				for (int i = 0; i < it->second.size(); i++)
				{
					vector<int>aa = it->first;
					aa.push_back(it->second[i]);
					if (it->second.size() == 2)
					{
						aa.push_back(it->second[(1 + i) % 2]);
						re.push_back(aa);
					}
					else
					{
						vector<int>bb = it->second;
						bb.erase(bb.begin() + i, bb.begin() + i + 1);
						newcandi[aa] = bb;
					}
				}
			}
			if (k == nums.size() - 2)
				return re;
			k++;
			candi = newcandi;
		}
	}
};

accepted



你可能感兴趣的:(LeetCode)