Permutations

来源:互联网 发布:软件系统可靠性指标 编辑:程序博客网 时间:2024/05/03 02:33
reference:http://blog.csdn.net/micx0124/article/details/9564233
class Solution {public:    vector<vector<int> > permute(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<vector<int> > vec;        int len=num.size(),i,j;        if(len == 0)return vec;        sort(num.begin(),num.end());        vec.push_back(num);        while(true){                        int left=-1,right=-1;            //find the position where num[j]<num[j-1] first come up, left=j            for(j=len-2;j>=0;--j){                if(num[j]<num[j+1]){                    left=j;                    break;                }//end if            }//end for            if(left>=0){                // find the first num[j] less than num[left] from right to left,right=j                for(j=len-1;j>=0;--j){                    if(num[j]>num[left]){                        right=j;                        break;                    }                }//end for                                swap(num[right],num[left]);                ++left;                right=len-1;                //flip the num from left+1 to len-1                while(left<right){                    swap(num[left++],num[right--]);                }                vec.push_back(num);            }//end if            else{                break;            }        }//end for    }};

原创粉丝点击