欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

排列组合算法实现

程序员文章站 2022-05-21 23:22:19
...

排列数:

#include <iostream>
using namespace std;

int n, k;
int a[25] = { 0 };
int b[25] = { 0 };
int vis[25] = { 0 };

void dfs(int step) {
	if (step == k) {
		for (int i = 0; i < k; i++)
			cout << b[i] << " ";
		cout << endl;
	}
	else {
		for (int i = 0; i < n; i++)
			if (vis[i] == 0) {
				b[step] = a[i];
				vis[i] = 1;
				dfs(step + 1);
				vis[i] = 0;
			}
	}
}

int main() {
	cin >> n >> k;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	dfs(0);
	return 0;
}

组合数:

#include <iostream>
using namespace std;

int n, k;
int a[25] = { 0 };
int b[25] = { 0 };
int vis[25] = { 0 };

void dfs(int step,int startx) {
    if (step == k) {
        for (int i = 0; i < k; i++)
            cout << b[i] << " ";
        cout << endl;
    }
    for (int i = startx; i < n; i++) {
        if (vis[i] == 0) {
            b[step] = a[i];
            vis[i] = 1;
            dfs(step + 1, i + 1);
            vis[i] = 0;
        }
    }
}

int main() {
    cin >> n >> k;
    for (int i = 0; i < n; i++)
        cin >> a[i];
    dfs(0,0);
    return 0;
}
相关标签: 算法 dfs