题目:
Given two positive integers n and k, the binary string Sn is formed as follows:
S1 = “0”
Si = Si-1 + “1” + reverse(invert(Si-1)) for i > 1
Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).For example, the first 4 strings in the above sequence are:
S1 = “0”
S2 = “011”
S3 = “0111001”
S4 = “011100110110001”
Return the kth bit in Sn. It is guaranteed that k is valid for the given n.Example 1:
Input: n = 3, k = 1
Output: “0”
Explanation: S3 is “0111001”. The first bit is “0”.
Example 2:Input: n = 4, k = 11
Output: “1”
Explanation: S4 is “011100110110001”. The 11th bit is “1”.Example 3:
Input: n = 1, k = 1
Output: “0”Example 4:
Input: n = 2, k = 3
Output: “1”Constraints:
1 <= n <= 20
1 <= k <= 2n - 1
来源
思路:dfs
S1 = “0”
S2 = “0 1 1”
S3 = “011 1 001”
S4 = “0111001 1 0110001”
k如果是1,那么返回肯定是0
如果是2,返回肯定是1
如果是中间数,肯定是1
只要是前半段的,返回的都是固定的,如果是后半段,我们只需要找对应的前半段的数。
譬如,对于S4 (n=4),k=11,则length=15,mid=8,那么11对应的前半段数就是 8-(11-8) = 5
我们拿着k=5去S3(n=3)找,则length=7,mid=4,那么5对应的前半段数就是 4-(5-4) = 3
我们拿着k=3去S2(n=2)找,则length=3,mid=2,那么3对应的前半段数就是 2-(3-2) = 1
这时k=1,返回0,
拿着这个0再往回倒饬,S2那里就是1,S3那里就是0,S4那里就是1
所以结果是1.
其实,这道题用暴力解,python算出所有排序然后切片的那个值也能过。
class Solution:
def findKthBit(self, n: int, k: int) -> str:
len_list = [0]*(n+1)
len_list[1] = 1
for i in range(1, n+1):
len_list[i] = 2*len_list[i-1] + 1
# 打表出来,首个空着,因为是从1开始算 [0, 1, 3, 7, 15, 31, ...]
def dfs(n, k):
mid = len_list[n-1] + 1
if k == 1: return 0
elif k == 2: return 1
elif k < mid: # if k in the first half, go up
return dfs(n-1, k)
elif k == mid: # if k equals mid, return 1
return 1
else: # if k in the second half, go up and k equals its counterpart
return 1 - dfs(n-1, mid-(k-mid))
return str(dfs(n, k))