关于permutation的讲解,请参见http://blog.csdn.net/xuqingict/article/details/24840183
[updated 2014.7.30]
所有的Permutation无论是否有重复元素,直接使用下面的代码即可,
bool helper(vector<int> &num)
{
if(num.empty()) return false;
typedef vector<int>::iterator iter;
iter first=num.begin(), last=num.end();
--last;
if(first==last) return false;
while(last != first && !(*(last-1) < *last))--last; //此处直接使用!< 即可。。。
if(last==first) return false;
iter left=last-1,right=last;
last=num.end();
--last;
while(!(*left < *last))--last; //同上!!!
iter_swap(left,last);
reverse(right,num.end());
return true;
}
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
if(num.empty()) return vector<vector<int> >();
vector<vector<int> > ret;
sort(num.begin(), num.end());
do
{
ret.push_back(num);
}while(helper(num));
return ret;
}
下列题目的讲解均是基于上面的文章:
题1:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2