每日1題 10/24 找出數組模式(遞規, 0生成01 ,1生成10)
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
- For example, for
n = 3, the1strow is0, the2ndrow is01, and the3rdrow is0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
Example 1:
Input: n = 1, k = 1 Output: 0 Explanation: row 1: 0
Example 2:
Input: n = 2, k = 1 Output: 0 Explanation: row 1: 0 row 2: 01
Example 3:
Input: n = 2, k = 2 Output: 1 Explanation: row 1: 0 row 2: 01
Constraints:
1 <= n <= 301 <= k <= 2n - 1
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
#由0開始
if n == 1:
return 0
if k % 2 == 0:
#如果K是偶數, 查看上一行的 , 假設k=2, 那就是上前一行k=1處生成, 如果是0 他就是對映1
return 1 if self.kthGrammar(n-1, k//2) == 0 else 0
else:
return 0 if self.kthGrammar(n-1, (k+1)//2) == 0 else 1
# res=[0]*k
#超出記憶體限制
# for n in range(n):
# array = []
# for i in range(k):
# # print(f'i={i}, res={res}')
# if res[i] == 0:
# array.append(0)
# array.append(1)
# else:
# array.append(1)
# array.append(0)
# res = array
# # print(f'res={res}')
# # print(f'array={array}')
# # print(f'這題的n={n}, k={k}')
# return array[k-1]
---------------------------------------
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1: return 0
parent = self.kthGrammar(n - 1, ( (k-1) // 2 ) + 1)
rem = (k - 1) % 2
if parent == 0:
return 0 if rem == 0 else 1
else:
return 1 if rem == 0 else 0標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁