LeetCode Additive Number

Description:

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.


Solution:

還是一道不給數據範圍就嘗試DFS的題目……

我這裏用的方法比較暴力,還有一種更簡單的,因爲每次符合additive number的方法只要確定前兩個數字就好

<span style="font-size:18px;">&& i < tot + 10</span>
中加有一步加了這個判斷,意思就是超過10位的數字我們就不考慮了,實際上是個bug,萬一BigInteger呢?

但再考慮到題目說得這麼不嚴謹……


<span style="font-size:18px;">public class Solution {
	public boolean isAdditiveNumber(String num) {
		int n = num.length();
		long[] arr = new long[n];
		return dfs(0, 0, num, arr);

	}

	public boolean dfs(int tot, int current, String num, long[] arr) {
		if (tot == num.length()) {
			for (int i = 2; i < current; i++)
				if (arr[i - 2] + arr[i - 1] != arr[i])
					return false;
			if (current <= 2)
				return false;
			return true;
		}

		if (current >= 3
				&& arr[current - 3] + arr[current - 2] != arr[current - 1])
			return false;

		for (int i = tot; i < num.length() && i < tot + 10; i++) {
			long current_num = Long.parseLong(num.substring(tot, i + 1));
			arr[current] = current_num;
			if (num.charAt(tot) == '0' && current_num > 0)
				return false;
			if (dfs(i + 1, current + 1, num, arr))
				return true;
		}

		return false;
	}

}</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章