我正在解决DP问题,最长增加子序列,其中我通过两种不同的方法初始化了dp数组,并且对于相同的输入获得了不同的结果。
First method, where I got the wrong answer was: int dp[n] = {1};
Second method, again a wrong answer: int dp[n];
memset(dp, 1, sizeof(dp));
最后,当我使用“ for循环”手动初始化数组时,我得到了正确的答案。
三种初始化方法之间有什么区别?
输入:第一行(N,即数组的大小),下一行:数组元素
83
86 177 115 193 135 186 92 49 21 162 27 90 59 163 126 140 26 172 136 11 168 167 29 182 130 62 123 67 135 129 2 22 58 69 167 193 193 56 11 42 29 173 21 119 184 137 198 124 115 170 13 126 91 180 156 73 62 170 196 81 105 125 84 127 136 105 46 129 113 57 124 95 182 145 14 167 34 164 43 150 87 8 76 178
正确的输出:15
我对“ memset”和直接初始化的回答是14。使用for循环初始化后得到15。
用
you initialize the first element to
1
, and the rest to zero.用
you set all bytes to
1
, which means that each element in the array will be0x01010101
.The "correct" way to set all elements of an array to a specific value is to use the algorithm function
std::fill
orstd::fill_n
. Or use astd::vector
where you can pass a default value to the constructor for each element.