This problem is easy if we can use division. The idea is get the product of all numbers and division each of them to get the result we want. Linear time and constant space.
Here we can't use this method. One intuitive thinking is: I can get the product from the first one to each number in the array and do it in the opposite direction. By observation, it's clear that by jumping one node we can get the product without it.
vector<int> productExceptSelf(vector<int>& nums) {
int len=nums.size();
vector<int> res;
if(!len) return res;
vector<int> forw(1,1);
vector<int> back(1,1);
for(int i=0;i<len-1;i++)
{
forw.push_back(forw[i]*nums[i]);
back.push_back(back[i]*nums[len-i-1]);
}
for(int i=0;i<len;i++)
{
res.push_back(forw[i]*back[len-i-1]);
}
return res;
}