combinatorics related algorithms e.g. unique BST(leetCode95), Permutations(46), Unique Path(62). Give an integer m
, how many different combinations can have? mathematically, it’s a permutation P_m^m
or combination C_m^n
problem, the total number is easy to calculate, but how to write a code to print out each combination elegantly ?
one core step: how to generate a new combination(k+1) array by inserting one new element into the current combination(k). e.g.
{1, 2} --> {3, 1, 2}, {1, 3, 2}, {1, 2, 3}
here is basically insert 3
at (k+1) positions, and each new position will generate a new combination with (k+1) size. depends on the problem, choose either vector
(to support random access) or list
(to support O(1) insert or delete) as the container.
one tip here, how to erase one element from std::list while iterating ?
|
|
this implementation is more clear than what I did in Permutation
while the memory of many last layers vector> actually are not in using. how to recycle the memory ?
|
|