又是排列组合,但使用 34. Permutations 中的解法却依然可以。
在那道题里,我说先偷个懒,使用 STL 中的算法,后面再详细补充。而这道题,我依然想偷懒一次。
但详细的部分却可以参考 89. Next Permutation
中的解法。在这道题中,我基本实现了
std::next_permutation。所以也并不存在无耻的使用
STL 函数逃避思考的问题了。
更详细的探秘,还可以参考我的这篇小文。
不愿重复造轮子了,且这个轮子还是我造的。。。
#include <vector>
using std::vector;
#include <algorithm>
using std::next_permutation; using std::sort;
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
vector<vector<int>> retv;
sort(num.begin(), num.end());
do {
retv.push_back(num);
} while (next_permutation(num.begin(), num.end()));
return retv;
}
};