Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二维数组填充 #103

Open
Twlig opened this issue Jun 13, 2022 · 0 comments
Open

二维数组填充 #103

Twlig opened this issue Jun 13, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Jun 13, 2022

在做最长公共子序列这道题时,需要采用一个二维数组

错误示范:

let dp = new Array(m + 1).fill(new Array(n + 1).fill(0))

上面是我最开始采用的填充方法,貌似看上去没问题,但是在实际使用时

dp[1][0] = 1

image
每一个都变成了1。反思了一下,应该是由于fill填充的是数组,相当于把new Array(n + 1)这个新数组的引用地址赋值给了new Array(m + 1)的每一个元素,导致每一个元素实际都是对应同一个array数组对象地址

正确用法

let dp = new Array(m + 1).fill(0).map(val => new Array(n + 1).fill(0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant