我正在尝试实现以下功能:
例如:
$a=array(1,10,25,50);
$number=15;
o/p : 15=1+1+1+1+1+10;
答案 0 :(得分:1)
完成:
extend array by inserting the upcoming value suppose you have
var array: [String] = ["Iphone4", "Iphone5", "Iphone6"]
//all the table functions here which are boiler plate//
then
var newValue = textbox.text
array.append = newValue
tablewview.reloadData()
此方法也是:
$a=array(1,10,25,50);
rsort($a);
$number=15;
$final = [];
$remainder = $number;
foreach($a as $num) {
do {
if($num <= $number) {
$final[] = $num;
$remainder -= $num;
}
if($remainder == 0) break;
} while($remainder >= $num);
}
echo $number . " = " . implode(' + ', $final);
答案 1 :(得分:1)
为此创建一个递归函数:
function getcomb($arr,$actualNum, $total=0, $combination_array = array()){
foreach($arr as $k=>$v){
if($v > $actualNum) continue;
$shiftVal = $v;
if($total+$shiftVal <= $actualNum ){
$combination_array[] = $shiftVal;
$total += $shiftVal;
$reminder = $actualNum-$total;
//echo "<pre>combination_array";print_r($combination_array);
if($reminder <= 0){
return $shiftVal;
}else{
return $shiftVal .' + '.getcomb($arr, $actualNum,$total, $combination_array);
}
}
}
}
$a=array(1,10,25,50);
rsort($a);
$number=15;
echo $str = getcomb($a, $number);