【Leetcode_總結】967. 連續差相同的數字 - python
阿新 • • 發佈:2019-01-07
Q :
返回所有長度為 N
且滿足其每兩個連續位上的數字之間的差的絕對值為 K
的非負整數。
請注意,除了數字 0
本身之外,答案中的每個數字都不能有前導零。例如,01
因為有一個前導零,所以是無效的;但 0
是有效的。
你可以按任何順序返回答案。
示例 1:
輸入:N = 3, K = 7 輸出:[181,292,707,818,929] 解釋:注意,070 不是一個有效的數字,因為它有前導零。
示例 2:
輸入:N = 2, K = 1 輸出:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
連結:https://leetcode-cn.com/problems/numbers-with-same-consecutive-differences/
思路:主要就是一個遍歷的過程,對於每次一遍歷的末位,分別加K或者-K,判斷是否大於0,記錄下來,思路很傻,效率不好,效率不好的原因主要是由於各種int轉str 這個很消耗時間
程式碼:
class Solution: def numsSameConsecDiff(self, N, K): """ :type N: int :type K: int :rtype: List[int] """ if N == 0: return [] if N == 1: return [i for i in range(10)] res = [str(i) for i in range(1, 10)] while N > 1: r1 = [] r2 = [] for i in range(len(res[:])): temp1 = int(res[i][-1]) - K temp2 = int(res[i][-1]) + K if temp1 < 10 and temp1 >= 0: r1.append(res[i] + str(temp1)) if temp2 < 10 and temp2 >= 0: r2.append(res[i] + str(temp2)) res = [] res += r1 res += r2 N -= 1 res_ = [int(r) for r in res] return list(set(res_))