#include <iostream>
#include <vector>
#include <algorithm>

void nextPartialPerm(std::vector<int> &z, int n1, int m1) {
    
    int p1 = m1 + 1;
    
    while (p1 <= n1 && z[m1] >= z[p1])
        ++p1;
    
    if (p1 <= n1) {
        std::swap(z[p1], z[m1]);
    } else {
        std::reverse(z.begin() + m1 + 1, z.end());
        p1 = m1;
        
        while (z[p1 + 1] <= z[p1])
            --p1;
        
        int p2 = n1;
        
        while (z[p2] <= z[p1])
            --p2;
        
        std::swap(z[p1], z[p2]);
        std::reverse(z.begin() + p1 + 1, z.end());
    }
}

int main() {
    std::vector<int> z = {1, 2, 3, 4, 5, 6, 7};
    int m = 3;
    int n = z.size();
    
    const int nMinusK = n - m;
    int numPerms = 1;
    
    for (int i = n; i > nMinusK; --i)
        numPerms *= i;
    
    --numPerms;
    
    for (int i = 0; i < numPerms; ++i) {
        for (int j = 0; j < m; ++j)
            std::cout << z[j] << ' ';
        
        std::cout << std::endl;
        nextPartialPerm(z, n - 1, m - 1);
    }
    
    // Print last permutation
    for (int j = 0; j < m; ++j)
            std::cout << z[j] << ' ';
        
    std::cout << std::endl;
    
    return 0;
}