题解 | #蛇形矩阵#
蛇形矩阵
https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e
方法1-通项公式
通过数学推导求得通项公式。
def aij(i, j): return int((j-1)*(i+1) + (j-1)*(j-2)/2 * 1 + (i-1)*(i-2)/2) + i n = int(input()) for i in range(1, n + 1): for j in range(1, n - i + 2): print(aij(i, j), end=' ') print()
分析思路:
观察可知,每一行是一个差成等差数列的二级等差数列
假设差对应的等差数列为:dn = p + (n-1)*q
a2 - a1 = p
a3 - a2 = p + q
a4 - a3 = p + 2*q
...
an - an-1 = p + (n-2)*q
所有等式相加得到:
an - a1 = (n-1)*p + (n-1)*(n-2)/2 * q + a1
求得通项公式为:an = (n-1)*p + (n-1)*(n-2)/2 * q + a1
行索引为i,每行的p=i+1, q=1
而每行的首项a1又成二级等差数列:(i-1)*(i-2)/2 + i
所以,每行每列的元素公式为:
aij = (j-1)*(i+1) + (j-1)*(j-2)/2 * 1 +(i-1)*(i-2)/2 + i
方法2-索引规律
从顺序矩阵到目标矩阵,找到索引规律。
n = int(input()) list1 = [[0] * i for i in range(1, n + 1)] # print(list1) # [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0]] a = 0 for i in range(n): for j in range(i + 1): a = a + 1 list1[i][j] = a # print(list1) # [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]] # 观察每行的索引规律: # [0,-1],[1,-1],[2,-1],[3,-1] # [1,-2],[2,-2],[3,-2] # [2,-3],[3,-3] # [3,-4] # 观察得知j从1到n,i从j-1到n for j in range(1, n + 1): for i in range(j - 1, n): print(list1[i][-j], end=" ") print()
方法3-循环计算首项和公差
一开始没写出通项公式,所以直接通过循环来计算首项和公差。
n = int(input()) a1_list = [(i+1)*i/2 + 1 for i in range(n)] d1_list = [2+i for i in range(n)] li = [[] for _ in range(n)] for i in range(n): li[i] = [a1_list[i]] d = d1_list[i] a = a1_list[i] for j in range(n-i-1): a += d li[i].append(a) d += 1 for i in range(len(li)): for j in range(len(li[i])): print(int(li[i][j]), end=' ') print()
【牛客站内】华为机试题解 文章被收录于专栏
【牛客站内】 分享个人刷题的思路和解法