# C++ 3-line O(k) Time O(1) Space Solution

• class Solution {
public:
vector<int> getRow(int n) {
vector<int> result = {1};
for (double i = 1; i <= n; ++i)
result.push_back(result.back() * (n - i + 1) / i);
return result;
}
};

• Weird thing is that your i is type double, and it indeed worked. I had the exact same approach as yours but with int type i in the for loop, and it doesn't pass.

WHY!?

• I use double when I dealing operations with large number times/divided by numbers. It's just safer this way.
One advantage of double in those cases is it is less likely to be overflowed.
If you use "int" type, the intermediate number will be too large and overflow.
I just tested "long" and it does work too. But still, I just blindly used double because it is safer and I don't really need worry about whether long or int is enough.

• @fentoyal Thank you for your reply, correct me if I am wrong.

so, if i is "int", then

result.back() * (n - i + 1) / i

will overflow.

But if i is "double", then by diving, the result is converted to double, which means the large number is safely stored.

What you are doing is indeed a good programming habit, I just learnt something today, thanks!

• @SebastianZhou
Actually, we probably can guarantee the number AFTER dividing should never overflow, because OJ provided a vector of INT to store the results. So the reason is not about the number AFTER dividing.
I chose double because there is an intermediate (temporary) number -- the product of result.back() * (n - i + 1) -- this one is BEFORE dividing, and can easily overflow. Using double can handle this corner case.

A simpler example can be like this: we know INT_MAX is 2147483647
now you let a = 2147483647;
If you do something like b= a * 2 / 4 (without a smart compiler that will deduce it to a / 2 in compile time), you won't get right result, because a * 2 overflows and becomes some negative number, and then this negative number is divided by 4.
Using double or long or long long can avoid this problem. This is some trick I learned over time too.

• i have a diffrent with you,I put i ahead,to ensure it not overflowed,
result.back() / i * (n - i + 1)
then ,I am wrong,why?

• @chenpuyang