码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Permutations"

时间:2014-08-02 05:11:02      阅读:199      评论:0      收藏:0      [点我收藏+]

标签: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

LeetCode "Permutations"

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/tonix/p/3886239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!