題目:
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]解析:
STL庫中有解決次類題目的函數,如果給定的數組是遞增的那麼我們可以調用next_permutation()函數,反之,遞減數組可以調用prev_permutation()函數,如果無序的則可以先排序再根據情況調用,此題我就是先排序後直接調用函數解決的。
程序答案:
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > result;
sort(num.begin(),num.end());
result.push_back(num);
while (next_permutation(num.begin(),num.end()))
{
result.push_back(num);
}
return result;
}
};