leetcode 之Permutation(七)
首先是next permutation的算法的描述和分析如下:
这题一是要知道思路,编程中注意STL的用法
void nextPermutaion(vector<int> &num) { next_permutation(num.begin(), num.end()); } private: template<typename BidiIt> bool next_permutation(BidiIt first, BidiIt last) { //反向,注意! auto rfirst = reverse_iterator<BidiIt>(last); auto rlast = reverse_iterator<BidIt>(first); auto pivot = next(rfirst); while (pivot != rlast && *pivot > *prev(pivot)) pivot++; if (pivot == rlast) { reverse(rfist, rlast); return false; } //注意用法 auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot)); swap(*pivot, *change); reverse(rfirst, pivot); return true; }
接着是Permutation Sequence
有人用康托编码来解这个问题,不过个人觉得不太好理解,其实完全可以用上题的思路
string getPermutaion(int n, int k) { string s(n, '0'); for (int i = 0; i < n; i++) s[i] += i + 1; for (int i = 0; i < k; i++) next_permutation(s.begin(), s.end()); return s; }