[面试] 组合(非递归)

接上题排列,稍作修改就可以做一个非递归的组合数了。

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

void permutation(int a[], int n, int k)
{
    vector<int> b(k);

    stack<int> s;

    s.push(-1);

    while(!s.empty())
    {
        if (s.size() > k)
        {
            for(int i = 0; i < k; i++)
                cout << b[i] << ' ';
            cout << endl;
            s.pop();
            continue;
        }

        int start = s.top() + 1;
        s.pop();
        for(int i = start; i < n; i++)
        {
            b[s.size()] = a[i];
            s.push(i);
            s.push(i);
            break;
        }
    }
}

int main()
{
    int a[] = {1, 2, 3};

    int aSize = sizeof(a) / sizeof(int);

    permutation(a, aSize, 2);
}
原文地址:https://www.cnblogs.com/chkkch/p/2748927.html