This paper mainly introduces the implementation of PHP backtracking algorithm, combined with specific examples of the implementation of the PHP backtracking algorithm and the use of methods, involving strings and arrays of recursion, traversal, operation and other related operations skills, the need for friends can refer to, hope to help everyone.
Problem:
A bull camel 2 bags of rice, a cow camel a bag of rice, two calf camel a bag of rice, ask 100 bags of rice How many head Daniel, how many heads of cattle, how many calves?
Implementation code:
<?php/* * k = 2x + y + 1/2z value range * 0 <= x <= 1/2k * 0 <= y <= k * 0 <= Z < = 2k * x, y, z max 2k */$daMi $result = Array (), function isOk ($t, $daMi, $result) {/*{{{*/$total = 0; $hash = array (); $hash [1] = 2; $hash [2] = 1; $hash [3] = 0.5; for ($i =1; $i <= $t; $i + +) {$total + = $result [$i] * $hash [$i];} if ($total <= $daMi) {return true;} return false;} /*}}}*/function Backtrack ($t, $daMi, $result) {/*{{{*///Recursive exit if ($t > 3) {//Output optimal solution if ($daMi = = (2 * $result [1] + $result [2 ] + 0.5 * $result [3]) { echo "optimal solution, Rice: ${dami}, Daniel: $result [1], Medium bull: $result [2], calf: $result [3]\n";} return;} for ($i = 0; $i <= 2 * $daMi, $i + +) {$result [$t] = $i,//Pruning if (IsOk ($t, $daMi, $result)) { backtrack ($t +1, $daMi, $result);} $result [ $T] = 0; }}/*}}}*/backtrack (1, $daMi, $result);? >
Running results such as: