LeetCode 458. Poor Pigs
原题链接
困难
作者:
JasonSun
,
2020-01-16 00:24:32
,
所有人可见
,
阅读 990
Algorithm (Math)
- If there are only two pigs and 15mins test pereiod, then we can form a 5x5 matrix and use one pig to test the row and another one to test the column.
- With 3 pigs we instead of a 5x5 matrix will get a 5x5x5 cube.
- So the problem becomes solvable by finding the smallest $n$-dimensional cube whose volume is larger than
buckets
. This could be done either using binary search or just linear scan. We settle for linear scan.
Code
template <class F>
struct recursive {
F f;
template <class... Ts>
decltype(auto) operator()(Ts&&... ts) const { return f(std::ref(*this), std::forward<Ts>(ts)...); }
template <class... Ts>
decltype(auto) operator()(Ts&&... ts) { return f(std::ref(*this), std::forward<Ts>(ts)...); }
};
template <class F> recursive(F) -> recursive<F>;
auto const rec = [](auto f){ return recursive{std::move(f)}; };
class Solution {
public:
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
const int n = minutesToTest / minutesToDie;
const int solution = rec([&](auto && f, int acc, int count) -> int {
if (acc < buckets)
return f(acc * (n + 1), count + 1);
else
return count;
})(1, 0);
return solution;
};
这个就太秀了啊