The problem is codewars, in short: finding and combining different integers for an integer. Https://en.wikipedia.org/wiki/Partition_ (Number_theory)
For example: The combination of integers with 6 has the following 11 kinds,
6
5 + 1
4 + 2
4 + 1 + 1
3 + 3
3 + 2 + 1
3 + 1 + 1 + 1
2 + 2 + 2
2 + 2 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
Solution One:
To avoid repetition, we can choose to gradually decrement the first addend until it is not less than half of N (keep the number of decomposition), then apply this strategy to the first addend, or take 6 as an example:
6
5 + 1
4 + 2
3 + 3
Then apply this strategy to the first Addend 5,
4 + 1
3 + 2
Then apply this strategy to decomposition 4 and 3 to get the following:
6
5 + 1
4 + 1 + 1
3 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
2 + 2 + 1 + 1
3 + 2 + 1
4 + 2
2 + 2 + 2
3 + 3
Because we already have the 3+2+1, for 4 is not decomposed into 3+1+2, here the limitations of the decomposition 4 can not produce than 2 (4 after the 2) small number, so can only be the three, the same, 3 will no longer decompose, because the decomposition is not more than 3 (the latter) is larger than the number.
1 defexp_sum (n):2 ifN <0:3 return04 ifn = =0:5 return16 returnHelp (N, 1)7 8 defHelp (n, mini):9TMP = 1Ten ifN <= 1: One return1 A forIinchRange (1, n/2+1):##保证n-I not less than I - ifI >=Mini: # # Ensure that the number of decomposition is not less than the smaller number behind -TMP = tmp + Help (N-I, i) the returntmp - PrintExp_sum (6)
View Code
Of course, this recursive speed is very slow, t (n) = t (n-1) + t (n-2) +...+ t (ceil (N/2)), the time complexity is exponential level.
Solution Two:
You can open a list of size n to store the results that have been computed:
1 defexp_sum (n):2 ifN <0:3 return04 ifn = = 0orn = = 1:5 return16solution = [1] + [0]*N7 8 forIinchRange (1, N):9 forJinchRange (I, n+1):TenSOLUTION[J] + = solution[j-i] One returnSolution[n]+1
View Code
Solution Three:
According to generation function on Wikipedia:P(k) = p(k − 1) + p(k − 2) − p (k −5) − p(k −7) + p(k −12) + p(k −15) − P (k −22) − ... + ( -1) ^ (k+1) *P(k − (3k^2-k)/2) + ( -1) ^ (k+1) *P(k − (3k^2 + k)/2)
1 defexp_sum (n):2Solutions = [1]* (n + 1)3 4 forIinchXrange (1, n + 1):5J, K, s = 1, 1, 06 whileJ >0:7j = i-(3 * k * k + k)/28 ifJ >=0:9s + = ( -1) * * (k+1) *Solutions[j]Tenj = i-(3 * k * k-k)/2 One ifJ >=0: As + = ( -1) * * (k+1) *Solutions[j] -K + = 1 -Solutions[i] =s the - returnSolutions[n]
View Code
Reference Links:
Https://en.wikipedia.org/wiki/Partition_ (Number_theory)
Http://stackoverflow.com/questions/438540/projecteuler-sum-combinations
2015-07-15 17:03:25
PARTITION (number theory) ALSO explosive number in Codewars