413. 等差数列划分
1、这题看起来简单点。f(i,j)表示到从i到j是不是等差数列。若f(i,j-1)为等差数列,则取决于nums[j]-nums[j-1]是否等于nums[j-1]-nums[j-2];若不为,则不为。
i遍历数组即可。
2、过了哈哈
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
n = len(nums)
count = 0
for i in range(0,n-2):
first = nums[i+1]-nums[i]
for j in range(i+2,n):
if nums[j]-nums[j-1]==first:
count = count + 1
else:
break
return count
91. 解码方法
1、这题好像也不难,设f(n)表示长度为n的序列有多少种解释方法。
f(n) = f(n-2)+[3种/2种]
2、错了鹅鹅鹅
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
pre_0 = 0
pre_1 = 1
if n%2 == 0:
for i in range(0,n,2):
new_0 = 0
if int(s[i])>0:
new_0 += 1
if int(s[i+1])>0:
new_0 += 1
if 1<=int(s[i:i+2])<=26:
new_0 += 1
result = pre_0 + new_0
pre_0 = result
else:
for j in range(1,n,2):
new_1 = 0
if int(s[j])>0:
new_1 += 1
if int(s[j+1])>0:
new_1 += 1
if 1<=int(s[j:j+2])<=26:
new_1 += 1
result = pre_1 + new_1
pre_0 = result
return result
原因大概为把“12”解释为3种,1,2,12,其实(1,2)应该是1种
3、两个两个跳跃感觉太快了,中间有很多情况被忽略
4、一个一个跳,条件重复
5、看了答案貌似是转移方程错了
6、到n为1位还是2位,这种讨论不会使情况重复
7、多次尝试后,终于过了。还是要考虑n=1的情况,已经状态方程的准确性
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
dp=[0]*n
if n==1:
if int(s[0])>0:
return 1
else:
return 0
if int(s[0])>0:
dp[0] = 1
else:
dp[0] = 0
if int(s[0])>0 and int(s[1])>0:
dp[1] = dp[1]+1
if int(s[0:2])>=10 and int(s[0:2])<=26:
dp[1] = dp[1]+1
for i in range(2,n):
if int(s[i])> 0:
dp[i] = dp[i]+dp[i-1]
if int(s[i-1:i+1])>=10 and int(s[i-1:i+1])<=26:
dp[i] = dp[i] + dp[i-2]
return dp[n-1]```
8、换成了滚筒。需要注意的是,这里每次的result都要重新置零,相当于第n个位置只与n-1和n-2有关,不保存其他值。
```bash
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
dp_1 = 0
if n==1:
if int(s[0])>0:
return 1
else:
return 0
if int(s[0])>0:
dp_0 = 1
else:
dp_0 = 0
if int(s[0])>0 and int(s[1])>0:
dp_1 = dp_1+1
if int(s[0:2])>=10 and int(s[0:2])<=26:
dp_1= dp_1+1
if n==2:
return dp_1
for i in range(2,n):
result = 0
if int(s[i])> 0:
result = result+ dp_1
if int(s[i-1:i+1])>=10 and int(s[i-1:i+1])<=26:
result = result + dp_0
dp_0 = dp_1
dp_1 = result
return result
截图留念