本文主要是介绍九层循环,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
From : Moli的编程
1-9数字组成3个数 abc, cde, fgh 且 abc:def : ghi = 1 : 2 : 3
g(x, y, z) {x * 2 == y & x * 3 == z && printf("%d, %d, %d\n", x, y, z);
}
f(i, j, m, r) {i ? 1 << j & m || f(i - 1, 1, m | 1 << j, r * 10 + j), j < 10 && f(i, j + 1, m, r): g(r / 1000000, r / 1000 % 1000, r % 1000);
}
main() {f(9, 1, 0, 0);}
程序解压
#include <stdio.h>
void outputIfValid(int abc, int def, int ghi) {if (abc * 2 == def && abc * 3 == ghi)printf("%d, %d, %d\n", abc, def, ghi);
}// 第 i 层 for 循环, m 以 bit set 表示已使用的数字, r 为当前排列abcdefghi
void f(int i, int m, int r) {if (i == 0)outputIfValid(r / 1000000, r / 1000 % 1000, r % 1000);elsefor (int j = 1; j < 10; j++) {if (((1 << j) & m ) == 0)f(i - 1, m | (1 << j ), r * 10 + j);
}
int main() {f(9, 1, 0);
}
c++ 03 版, 采用std::next_permutation
#include <algorithm> // std::next_permutation
#include <numeric> // std::iota
#include <iostream>
using namespace std;
int main() {int a[9];iota(a, a + 9, 1); // 1, 2 ... 9do {int abc = a[0] * 100 + a[1] * 10 + a[2];int def = a[3] * 100 + a[4] * 10 + a[5];int hig = a[6] * 100 + a[7] * 10 + a[8];if (abc * 2 == def && abc * 3 == hig) cout << abc << " " << def << " " << hig << endl;} while (next_permutation(a, a + 9));
这篇关于九层循环的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!