我有一定的困難,這個算法問題。假設您必須使用(x)數量的數量,查找給定總和(y)的所有可能結果。搞清楚如何循環的方式,(X數之和= Y)
因此,假設我的x = 3,我的總和是60.我必須找出所有可能的情況。例如 1,1,58
,1,2,57
等...這有點複雜,但在這裏並不重要。
我可以計算出X = 2,X = 3,但它正在手工完成,我需要弄清楚如何動態地做到這一點。
for ($first=$start; $first <= $highest_number; $first++) { //start = 1, highest_number = y/x which is 20 in this case.
for ($inc=$start; $inc <= $end; $inc++) { //end = 40
if ($x>= 3) { //assuming x = 3
for ($n=$highest_number; $n <= $end ; $n++) {
if ($first + $inc + $n == $target) {
$result['result'][] = $first .",". $inc .",". $n;
}
}
} else { // assuming x = 2
if ($first + $inc == $target) {
$result['result'][] = $first .",". $inc;
}
}
}
}
這就是我卡住的地方。所以很明顯,我現在使用的條件爲x = 2,x = 3。什麼是最好的動態做法?我想遞歸函數,我沒有什麼工作,但是這是我想象它看起來:
//recursion - does not work, not sure how to make it work
$z = 1;
function test($x, $first, $inc){
while ($z<= $x) {
//this is where I'm stuck. How do i form my loop so that it works dynamically.
for ($n=$start; $n <= $end ; $n++) {
}
}
}
任何人都可以就如何使其佔任何數量的形成我的遞歸函數的提示x在方程中?
遞歸似乎是要走的路。選擇結果中的第一個數字,從'y'中減去它,然後用'y = y-first'和'x = x-1'遞歸。當'y
Barmar
X嵌套循環 - 產生陣列,其中子陣列都具有長x –
看起來像Ÿ^ x的循環迭代(假設如1,59不一樣59,1)的陣列,除非我誤解你正在嘗試做 –