PHP取陣列中幾個數值求和等於指定值的演算法
阿新 • • 發佈:2019-01-10
沒有找到PHP版本的 貼一下參考C#的
$_arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); function getSetBySum($_array, $_sum, $_index, $_current, $_return=''){ for($i = $_index; $i < count($_array); $i++){ if($_current-$_array[$i] == 0 && $_sum-$_array[$i] ==0){ //找到一個 $_return .= $_array[$i].'<br/>'; echo $_return; }else if($_current-$_array[$i] > 0 ){ //繼續找 $_return .= $_array[$i].','; $_sum -= $_array[$i]; for( $j = $i+1; $j<count($_array); $j++){ getSetBySum($_array,$_sum,$j,$_current-$_array[$i],$_return); } } } } for($t = 0; $t < count($_arr); $t++){ getSetBySum($_arr,20,$t, 20); }