全排列算法c++实现

问题:

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

Solution:

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    vector<vector<int> > permute(vector<int> &num)
    {
        vector<vector<int> > resultVector;
        sort(num.begin(),num.end());//STL algorithm funtion
        do
        {
            vector<int> vOne;
            for(int i=0;i<num.size();i++)
                vOne.push_back(num[i]);
            resultVector.push_back(vOne);
        }while(next_permutation(num.begin(),num.end()));//next_permutation you can find in STL
        return resultVector;
    }
    vector<vector<int> > permuteOrder(int n)
    {
        vector<int> num;
        for(int i=1;i<=n;i++)
            num.push_back(i);
        return permute(num);
    }
    void printCollection(vector<vector<int> > &vResult)
    {
        for(vector<vector<int> >::const_iterator iter = vResult.begin();iter!=vResult.end();iter++)
        {
            for(vector<int>::const_iterator it = (*iter).begin();it!=(*iter).end();it++)
            {
                cout<<*it<<" ";
            }
            cout<<endl;
        }

    }
};
int main()
{
    vector<int> num ;
    num.push_back(1);
    num.push_back(3);
    num.push_back(2);
    Solution so;
    cout<<"permutation"<<endl;
    vector<vector<int> >  vResult = so.permute(num);
    so.printCollection(vResult);
    cout<<"order permutation"<<endl;
    vector<vector<int> >  vOrderResult = so.permuteOrder(3);
    so.printCollection(vOrderResult);
    
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值