1 Problem Statement
Pseudo-polynomialPartition
Given a set consisting of n integers [a1, a2, …an], you want to partition into two parts so that thesum of the two parts is equal. Suppose s = a1 + a2 …+ an. The time complexity of your algorithm shouldbe O(ns) orbetter. [Note: Due to the presence of the term s in the timecomplexity, such an algorithm is called pseudo polynomial algorithm.]
2 Theoretical Analysis
In this problem, I use part[i][j] to be true if asubset of {x1, x2,..,xj} sums to i and false otherwise. Thus, part[i][j] istrue if either p(i, j-1) is true or if part(i–xj, j-1) is true.
part(i, j) is false otherwise. And suppose s is thesum of the array.
Thus, the total time complexity is O(ns)
3 Experimental Analysis
3.1 Program Listing
I use python to write the program, if the O(ns) istoo small, the running time does not change obviously.
Thus, I choose “S”: 500, 1000, 1500, 2000, 2500
And, keep “N”: 6
3.2 Data Normalization Notes
I normalize the values by a constant of 679.91 It comes from theradio of average experimental result and average theoretical result.
3.3 Output Numerical Data
s | n | Experimental Result, in ns | Theoretical Result | Scaling Constant | Adjusted Theoretical Result |
500 | 6 | 1699924.46 | 3000 |
| 2039723.46 |
1000 | 6 | 4694938.65 | 6000 |
| 4079446.91 |
1500 | 6 | 6446910.85 | 9000 |
| 6119170.37 |
2000 | 6 | 8310079.57 | 12000 |
| 8158893.83 |
2500 | 6 | 9443998.33 | 15000 |
| 10198617.3 |
|
| 6119170.37 | 9000 | 679.91 |
|
3.4 Graph
3.5 Graph Observations
From the graph, we can see the blue line, derivesfrom experiment, fits the red line which comes from theory.
4 Conclusions
From the experiment, we can come to a conclusionthat the time complexity of this code problem is O(ns).
# -*- coding: UTF-8 -*-
# __author__ = 'Sengo'
import time
def open_clock(func):
def _wrapper(*args, **kwargs):
begin = time.time()
ret = func(*args, **kwargs)
end = time.time()
total = end - begin
print "cost time: ", total
return ret
return _wrapper
@open_clock
def find_partition(arr):
"""
:param arr: A list of integers arr
:return: True if arr can be partitioned, and sum of two part is equal
"""
_sum = sum(arr)
n = len(arr)
# Odd sum
if _sum % 2:
return False
# init part[_sum/2+1][n+1]
part = [[0] * (n+1) for _ in range(_sum/2+1)]
# init top row as True
for i in range(n+1):
part[0][i] = True
# init the leftmost column as False, expect part[0][0]
for i in range(1, _sum/2 + 1):
part[i][0] = False
for i in range(1, _sum/2 + 1):
for j in range(1, n + 1):
part[i][j] = part[i][j-1]
if i >= arr[j-1]:
part[i][j] = part[i][j] or part[i - arr[j-1]][j-1]
return part[_sum/2][n]
if __name__ == '__main__':
a = [0, 1000, 0, 0, 0, 1000]
print find_partition(a)
参考
http://www.geeksforgeeks.org/dynamic-programming-set-18-partition-problem/
https://en.wikipedia.org/wiki/Partition_problem