AMD 確認 Zen 4 架構 EPYC 處理器將支援 12 條 DDR5 記憶體通道
阿新 • • 發佈:2021-12-09
給定一個數字字串 S,比如 S = "123456579",我們可以將它分成斐波那契式的序列 [123, 456, 579]。
形式上,斐波那契式序列是一個非負整數列表 F,且滿足:
0 <= F[i] <= 2^31 - 1,(也就是說,每個整數都符合 32 位有符號整數型別);
F.length >= 3;
對於所有的0 <= i < F.length - 2,都有 F[i] + F[i+1] = F[i+2] 成立。
另外,請注意,將字串拆分成小塊時,每個塊的數字一定不要以零開頭,除非這個塊是數字 0 本身。
返回從 S 拆分出來的任意一組斐波那契式的序列塊,如果不能拆分則返回 []。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/split-array-into-fibonacci-sequence
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
迭代
import java.util.*; class Solution { public List<Integer> splitIntoFibonacci(String num) { if (num == null || num.length() == 0) { return Collections.emptyList(); } long first = 0; for (int i = 0; i < num.length() && (i == 0 || first != 0); ++i) { first = first * 10 + num.charAt(i) - '0'; if (first > Integer.MAX_VALUE) { break; } long second = 0; for (int j = i + 1; j < num.length() && (j == i + 1 || second != 0); ++j) { second = second * 10 + num.charAt(j) - '0'; if (second > Integer.MAX_VALUE) { break; } List<Integer> ret = new ArrayList<>(); ret.add((int) first); ret.add((int) second); boolean init = true; long c = 0; long a = first, b = second; for (int k = j + 1; k < num.length() && (init || c != 0); ++k) { c = c * 10 + num.charAt(k) - '0'; if (c > Integer.MAX_VALUE || c > a + b) { break; } if (a + b == c) { ret.add((int) c); a = b; b = c; c = 0; init = true; if (k == num.length() - 1) { return ret; } } else { init = false; } } } } return Collections.emptyList(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { new Solution().splitIntoFibonacci(in.next()).forEach(System.out::println); } } }
遞迴
心之所向,素履以往 生如逆旅,一葦以航import java.util.LinkedList; import java.util.List; class Solution { private LinkedList<Integer> ret = new LinkedList<>(); public List<Integer> splitIntoFibonacci(String S) { backtracing(S, 0); return ret; } public boolean backtracing(String S, int start) { // 1. 終止條件 :start == len(res)內元素大於2個,就不需要繼續嘗試拆分了 if (start == S.length() && ret.size() > 2) { return true; } // 2. 遞迴過程 : 從start 往後拆分 long num = 0; for (int i = start; i < S.length() && (i == start || num != 0); i++) { num = num * 10 + S.charAt(i) - '0'; if (num > Integer.MAX_VALUE) { return false; } if (isFibonacciSequence((int) num)) { ret.offerLast((int) num); if (backtracing(S, i + 1)) { return true; } ret.pollLast(); } } return false; } // 判斷是否能組成斐波那契數列 public boolean isFibonacciSequence(Integer num) { if (ret.size() < 2) { return true; } Integer pre1 = ret.pollLast(); Integer pre2 = ret.pollLast(); ret.offerLast(pre2); ret.offerLast(pre1); return pre1 + pre2 == num; } public static void main(String[] args) { new Solution().splitIntoFibonacci("123456579").forEach(System.out::println); } }