【題目】LCP 02. 分式化簡
有一個同學在學習分式。他需要將一個連分數化成最簡分數,你能幫助他嗎?
連分數是形如上圖的分式。在本題中,所有係數都是大於等於0的整數。
輸入的cont代表連分數的係數(cont[0]代表上圖的a0,以此類推)。返回一個長度爲2的數組[n, m],使得連分數的值等於n / m,且n, m最大公約數爲1。
示例 1:
輸入:cont = [3, 2, 0, 2]
輸出:[13, 4]
解釋:原連分數等價於3 + (1 / (2 + (1 / (0 + 1 / 2))))。注意[26, 8], [-13, -4]都不是正確答案。
示例 2:
輸入:cont = [0, 0, 3]
輸出:[3, 1]
解釋:如果答案是整數,令分母爲1即可。
限制:
cont[i] >= 0
1 <= cont的長度 <= 10
cont最後一個元素不等於0
答案的n, m的取值都能被32位int整型存下(即不超過2 ^ 31 - 1)。
【解題思路1】倒序遍歷
class Solution {
public int[] fraction(int[] cont) {
int denominator = cont[cont.length-1], numerator = 1;
int addend = 1;
for(int i = cont.length - 2; i >= 0; i--){
numerator = denominator; //翻轉後分子變分母
denominator = cont[i] * denominator + addend; //求出通分後的分子,反轉後變爲分母
addend = numerator; //記錄翻轉後的分子以便下一次通分
}
return new int[]{denominator, numerator};
}
}
【解題思路2】遞歸 - 正序
class Solution {
private int[] recursive(int[] count, int index) {
if (index == count.length - 1) {
return new int[]{count[index], 1};
}
int[] nextRes = recursive(count, index+1);
return new int[]{count[index] * nextRes[0] + nextRes[1], nextRes[0]};
}
public int[] fraction(int[] cont) {
return recursive(cont, 0);
}
}