您的位置:首页 > 其它

46. Permutations

2016-05-09 19:12 260 查看
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]
.
【思路】求给定向量数组所有元素的全排列问题。

n个元素有n!种全排列,而STL底层文件<
algorithm >中有关于排列元素的标准算法:

bool next_permutation(BidirectionalIterator beg , BidirectionalIterator end);


该函数会改变区间[beg , end)内的元素次序,使它们符合“下一个排列次序”
bool prev_permutation(BidirectionalIterator beg , BidirectionalIterator end);


该函数会改变区间[beg , end)内的元素次序,使它们符合“上一个排列次序”

class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> re;
if(nums.size()==0) return re;
sort(nums.begin(), nums.end());
re.push_back(nums);
while(next_permutation(nums.begin(),nums.end()))
{
re.push_back(nums);
}
return re;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: