c++代码:可填在百位、十位、个位的数字都是1、2、3、4。组成所有排列中去掉不满足条件的排列
时间: 2024-10-13 10:17:17 浏览: 20
在C++中,你可以通过递归的方式来生成并过滤出所有符合条件的三位数的排列。这个过程可以分为两部分:生成所有三位数的排列,然后检查每个排列是否满足条件(百位、十位和个位的数字分别只能是1、2、3或4)。下面是一个简单的示例代码:
```cpp
#include <iostream>
#include <vector>
std::vector<int> digits = {1, 2, 3, 4};
void permute(int num, int start, std::vector<int>& permutation) {
if (start == 3) {
// 如果已经到达个位,就添加到结果列表中
permutation.push_back(num);
} else {
// 依次尝试四个数字
for (int digit : digits) {
permutation[start] = digit;
permute(num * 10 + digit, start + 1, permutation); // 递归下一个位置
}
}
}
bool isValidPermutation(int num) {
// 检查每一位是否都在1到4之间
return num >= 1 && num % 10 <= 4 && (num / 10) % 10 <= 4 && (num / 100) % 10 <= 4;
}
int main() {
std::vector<int> result;
permute(0, 0, result);
for (const auto& permutation : result) {
if (isValidPermutation(permutation)) {
std::cout << permutation << " ";
}
}
return 0;
}
```
在这个代码中,`permute`函数用于生成所有三位数的排列,而`isValidPermutation`函数检查一个排列是否满足条件。在`main`函数里,我们先生成所有的排列,然后筛选出有效的。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)