标签:style blog color io for ar div amp
Lexicographically algorithms:
1. Iterate array from back to front, and find the first decreasing point:
1,2,4,3 -- 4
2. Iterate array from back to front, again to find the first number larger than the previous number of the found one in #1:
1,2,4,3 -- 3
3. Swap the found two:
1,3,4,2
4. Reverse all elems from found index in #1 to the end:
1,3,2,4
class Solution { public: vector<vector<int> > permute(vector<int> &num) { std::sort(num.begin(), num.end()); vector<vector<int> > ret; ret.push_back(num); while(true) { vector<int> rlast = ret.back(); // Find decreasing item back->front int i; for(i = rlast.size() - 1; i > 0; i --) if(rlast[i] > rlast[i-1]) break; if(i == 0) break; int j = i - 1; int k; for( k = rlast.size() - 1; k > 0; k --) if(rlast[k] > rlast[j]) break; std::swap(rlast[j], rlast[k]); std::reverse(rlast.begin() + i, rlast.end()); ret.push_back(rlast); } return ret; } };
LeetCode "Permutations",布布扣,bubuko.com
标签:style blog color io for ar div amp
原文地址:http://www.cnblogs.com/tonix/p/3886239.html