用c++非递归写排列组合算法
时间: 2023-04-08 12:03:58 浏览: 118
可以使用以下代码实现非递归的排列组合算法:
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int combination(int n, int k) {
if (k > n) {
return 0;
}
return factorial(n) / (factorial(k) * factorial(n - k));
}
int permutation(int n, int k) {
if (k > n) {
return 0;
}
return factorial(n) / factorial(n - k);
}
int main() {
int n = 5, k = 3;
printf("%dC%d = %d\n", n, k, combination(n, k));
printf("%dP%d = %d\n", n, k, permutation(n, k));
return 0;
}
```
该代码使用了阶乘函数来计算组合数和排列数,同时使用了条件判断来避免出现无效的计算。
相关问题
用c++写排列组合算法
我可以回答这个问题。排列组合算法可以使用递归或循环来实现。以下是使用递归实现的示例代码:
```
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int permutation(int n, int r) {
return factorial(n) / factorial(n - r);
}
int combination(int n, int r) {
return permutation(n, r) / factorial(r);
}
int main() {
int n = 5;
int r = 3;
printf("Permutation of %d and %d is %d\n", n, r, permutation(n, r));
printf("Combination of %d and %d is %d\n", n, r, combination(n, r));
return 0;
}
```
这个程序可以计算给定 n 和 r 的排列和组合。
如何用c++非递归中序遍历二叉树
以下是C++非递归中序遍历二叉树的代码实现:
```cpp
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* cur = root;
while (cur != NULL || !s.empty()) {
while (cur != NULL) {
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
cout << cur->val << " ";
cur = cur->right;
}
}
int main() {
TreeNode* root = new TreeNode(1);
root->right = new TreeNode(2);
root->right->left = new TreeNode(3);
inorderTraversal(root); // 输出:1 3 2
return 0;
}
```