Fork me on GitHub

46. Permutations 排列数

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

解析

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

	vector<vector<int>> permute(vector<int>& nums) {

		vector<vector<int>> vecs;

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

		help(0, nums,vecs);

		return vecs;
	}
};

题目来源

posted @ 2018-01-27 21:00  ranjiewen  阅读(369)  评论(0编辑  收藏  举报