算法--递归(6)

旧城冷巷雨未停 提交于 2020-03-03 05:02:53

求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;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!