LeetCode Permutations

Permutations

Given a collection of 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].


遍历排列树的算法就这样写!
for(int i = cur; i < num.size(); ++i)
{
	swap(num[cur], num[i]);
	dfs(ret, num, cur+1);
	swap(num[cur], num[i]);
}

class Solution {
public:
    vector<vector<int> > permute(vector<int> &num) {
        vector<vector<int> > ret;
		dfs(ret, num, 0);
		return ret;
    }

	void dfs(vector<vector<int> >& ret, vector<int>& num, int cur)
	{
		if(num.size() == cur)
		{
			ret.push_back(num);
		}
		else
		{
			for(int i = cur; i < num.size(); ++i)
			{
				swap(num[cur], num[i]);
				dfs(ret, num, cur+1);
				swap(num[cur], num[i]);
			}
		}
	}
};



你可能感兴趣的:(算法,Class,Numbers)