今天做個小東西時候遇到一個問題,不知道是自己想入了死胡同了還是什么情況,覺得不應該是這樣,但是不記得有其他方法了。
問題是這樣出現的。一個平面上,一共12個位置, 位置與位置之間有特殊的連線,除開一個位置固定建筑物不變外,其他11個位置每個位置都有可能出現三種不同的建筑,連線一起的建筑不同會產生不同的結果,然后我要算出那種方式才是最佳的。玩過游戲孢子的同學應該知道我說的情況,答案早就有了只是想自己算一下,但是發現一共11層,要寫11次 for,然后不知道有沒簡單方法.... 附圖如下
uj5u.com熱心網友回復:
組合數總計3^11(3的11次方),可以使用遞回計算。
uj5u.com熱心網友回復:
可以使用佇列,或者遞回uj5u.com熱心網友回復:
int p[] = {1,1,1,1,1,1,1,1,1,1,1,1};
for (p[0] = 1; p[0] <4; p[0]++)
{
for (p[1] = 1; p[1] <4; p[1]++)
{
for (p[2] = 1; p[2] < 4; p[2]++)
{
for (p[3] = 1; p[3] < 4; p[3]++)
{
for (p[4] = 1; p[4] < 4; p[4]++)
{
for (p[5] = 1; p[5] < 4; p[5]++)
{
for (p[6] = 1; p[6] < 4; p[6]++)
{
for (p[7] = 1; p[7] < 4; p[7]++)
{
for (p[8] = 1; p[8] < 4; p[8]++)
{
for (p[9] = 1; p[9] < 4; p[9]++)
{
for (p[10] = 1; p[10] < 4; p[10]++)
{
k = Zonghe(0, 0, 0);
k=qiuhe(k, p);
Zonghe guding = Zonghe(0, 0, 0);
for (int i = 0; i < 11; i++)
{
if (p[i] == y)
{
guding.yule = guding.yule + 1;
}
if (p[i] == f)
{
guding.renkou = guding.renkou + 10;
}
if (p[i] == g)
{
guding.yule = guding.yule - 1;
}
}
kz = k + guding;
if (kz.yule >= 0)
{
if (diyige == 0)
{
zui = kz;
diyige = 1;
}
else
{
zui = bia(zui,kz,p);
}
}
}
}
}
}
}
}
}
}
}
}
}
想了半天還是不知道怎么遞回.......uj5u.com熱心網友回復:
這是排列組合問題可以不用遞回,把for回圈改為用陣列(進位)的方式就可以了
比如(以下程式相當于列印11個位置,每個位置有{0,1,2}3個元素的全組合)
int main()
{
int i, cnt[11] = {0}; //用陣列管理11層回圈,假設每層回圈的最大回圈數為3
while (cnt[0] < 3) //當最外層回圈計數小于最大回圈數則繼續回圈(也就相當于最外層for還沒結束時繼續回圈)
{
for (i=0; i<11; i++)
{
printf("%d ", cnt[i]); //列印當前每層回圈的回圈計數
}
printf("\n");
cnt[10]++; //最后一層回圈的回圈計數遞增
for (i=10; i>0; i--) //用模擬進位的方式(低位達到最大則高位+1,低位清0)
{//相當于兩層for的 i,j回圈,j++小回圈到頭,就要i++大回圈遞增,然后小回圈j繼續從0開始
if (cnt[i]==3) //如果回圈計數達到了回圈最大值
{
cnt[i] = 0; //則當前層回圈計數從頭開始
cnt[i-1]++; //上一層回圈計數遞增
}
}
}
}
uj5u.com熱心網友回復:
使用無限嵌套uj5u.com熱心網友回復:
#include <iostream>
using namespace std;
template<typename T>
void do_print(T& p, int k)
{
for (int i = 0; i < k; ++i)
cout << p[i];
cout << endl;
}
template<typename T>
void permutation_recursion(const T& c, T& p, int n, int k)
{
for(int i = 0; i != c.size(); i++)
{
p[n] = c[i];
if(n == k - 1)
do_print(p, k);
else
permutation_recursion(c, p, n + 1, k);
}
}
int main()
{
int k = 3;
string s("AB");
string p(k, 0);
permutation_recursion(s, p, 0, k);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/55044.html
標籤:C++ 語言
上一篇:對照Google評分卡,看看你的技術水平在什么段位?
下一篇:Java自學-圖形界面 表格
