题目一:
解题思路:
对数组连续求和,并找到一个小于0的最小值
取绝对值 + 1,就是要求的值
代码实现:
class Solution:
def minStartValue(self, nums: List[int]) -> int:
start_val = 1
curr_sum = 0
min_val = 1
for a in nums:
curr_sum += a
min_val = min(min_val, curr_sum)
if 0 <= min_val:
return 1
return abs(min_val) + 1
题目二:
解题思路:
遍历获得比k小的所有数字,然后列表从后往前遍历,找到最接近k的数字
更新次数 + 1,更新k = k - 最接近的数字
持续循环,知道遍历结束,或者k = 0
代码实现:
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
res = [1, 1]
curr_val = 2
while curr_val <= k:
curr_val = res[-1] + res[-2]
res.append(curr_val)
if res[-1] > k:
res.pop()
num = 0
idx = len(res) - 1
while k > 0:
while res[idx] > k:
idx -= 1
k -= res[idx]
num += 1
return num
题目三:
回溯 + 剪枝
代码实现:
class Solution:
def getHappyString(self, n: int, k: int) -> str:
char_lst = ['a', 'b', 'c']
res = []
def happy_help(n, path, res):
nonlocal char_lst
if n == 0:
res.append(''.join(path))
return
for ch in char_lst:
if ch == path[-1]:
continue
path.append(ch)
happy_help(n - 1, path, res)
path.pop()
for ch in char_lst:
happy_help(n - 1, [ch], res)
if len(res) < k:
return ''
return res[k - 1]
题目四:
解题思路:
动态规划,从前向后遍历
当遍历到idx索引位时,从idx向后遍历,索引为idx2,表示从idx获取几位数字作为当前数字;如果idx到idx2的数字小于k,则更新idx2下一位上的方案数dp[idx2 + 1] = dp[idx],表示当前位取idx到idx2的话,idx2 + 1前面一共可能的方案数是多少
代码实现:
class Solution:
def numberOfArrays(self, s: str, k: int) -> int:
dp = [0] * (len(s) + 1)
dp[0] = 1
max_num = pow(10, 9) + 7
for idx in range(len(s)):
if s[idx] == '0':
continue
for idx2 in range(idx, len(s)):
curr_num = int(s[idx:idx2 + 1])
if curr_num > k:
break
dp[idx2 + 1] += dp[idx]
dp[idx2 + 1] %= max_num
return dp[-1]