算法--递归(6)

求n个元素的全排列

理解:
n=1
v.pushback(a[n])
print v
return
for i = 1 to n
v.pushback(a[n])
fullArray(v,n-1)
v.pop_back()
print endl

#include <iostream>
#include <vector>
using namespace std;

void fullArray(vector<int>& v, int n, vector<int> v0, int& total)
{
    if (n==0)
    {
        v.push_back(v0[n]);
        size_t size = v.size();
        for (int i = 0; i < size; ++i)
        {
            cout << v[i] << ends;
        }
        total+=1;
        cout << endl;
        v.pop_back();
        return;
    }
    for(auto it = v0.begin(); it != v0.end(); it++)
    {
        int temp = it-v0.begin();
        int temp0 = *it;
        v.push_back(*it);
        v0.erase(it);
        fullArray(v, n-1,v0, total);
        v.pop_back();
        v0.insert(v0.begin()+ temp, temp0);
    }
}

int main()
{
    int n = 7;
    int total = 0;
    vector<int> v, v0;
    for (int k = 1; k <= n; ++k)
    {
        v0.push_back(k);
    }
    fullArray(v, n-1, v0, total);
    cout << endl << "total: " << total << endl;
    return 0;
}

写完之后看了一下网上的其他答案:
写的更加简洁

#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
    int temp=a;
    a=b;
    b=temp;
}
void perm(int list[],int low,int high)
{
    if(low==high)
    {
        for(int i=0;i<=low;i++)
            cout<<list[i];
        cout<<endl;
    }
    else
        {
        for(int i=low;i<=high;i++)
        {
            swap(list[i],list[low]);
            perm(list,low+1,high);
            swap(list[i],list[low]);
        }
    }
}
int main()
{
    int list[1000];
    int n = 3;
    for (int i = 0; i < n; ++i)
    {
        list[i] = i+1;
    }
    perm(list,0,n-1);
    return 0;
}

发布了89 篇原创文章 · 获赞 0 · 访问量 1602

猜你喜欢

转载自blog.csdn.net/qq_43410618/article/details/104610209
今日推荐