Year of the Ox seeking cattle: there is a cow, can give birth to 4 years old, one year, are born of the same cow, the 15-year-old neutered, no longer students, 20-year-old died, and asked how many head of cattle n years

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_42565994/article/details/102775145

Year of the Ox seeking cattle: there is a cow, can give birth to 4 years old, one year, are born of the same cow, the 15-year-old neutered, no longer students, 20-year-old death, asked how many head of cattle n years?

// 方法1:按照时间推移计算, 嵌套循环
function countcows($years) {
    $cows[] = 0;
    if($years < 4) return 1;
    for($i=4; $i <= $years; $i++) {
        for($j=0, $k=count($cows); $j<$k; $j++) {
            $age = $i - $cows[$j];
            if($age >= 4 && $age < 15) $cows[] = $i;
            else if($age == 20) unset($cows[$j]);
        }
    }
    return count($cows);
}
// 方法2:不断的计算每头牛的产出, 使用递归
function countcows2($years) {
    static $cows_num = 1;
    for($i=1; $i<=$years; $i++) {
        if($i >= 4 && $i < 15) {
            $cows_num ++;
            countcows2($years - $i);
        }
        if($i == 20) $cows_num --;
    }
    return $cows_num;
}

transfer:

echo countcows(29);
echo '<br/>';
echo countcows2(29);

Guess you like

Origin blog.csdn.net/qq_42565994/article/details/102775145