The Idea behind dynamic programming is, to (1) never compute the same result twice and (2) only compute results at demand and not precompute the whole thing as you do it.
So there is a solution needed for solve(arr, n, ans)
with ans < 1024
, n < 1000000
and arr = array[n]
. The idea of having dp[n][ans]
holding the number of results is reasonable, so dp size is needed as dp = array[n+1][1024]
. What we need is a way to distinguish between not yet computed results and available results. So memset(dp, -1, sizeof(dp))
and then as you already did dp[0][0] = 1
solve(arr, n, ans):
if (dp[n][ans] == -1)
if (n == 0) // and ans != 0 since that was initialized already
dp[n][ans] = 0
else
// combine results with current and without current array element
dp[n][ans] = solve(arr + 1, n - 1, ans) + solve(arr + 1, n - 1, ans XOR arr[0])
return dp[n][ans]
The advantage is, that your dp
array is only partially computed on the way to your solution, so this might save some time.
Depending on the stack size and n
, it might be necessary to translate this from a recursive to an iterative solution