Skip to content

Commit

Permalink
[10_recursive] one_two_step, nonrecursive version, done.
Browse files Browse the repository at this point in the history
  • Loading branch information
Liam0205 committed Oct 12, 2018
1 parent 07297f8 commit 5a374e0
Showing 1 changed file with 48 additions and 4 deletions.
52 changes: 48 additions & 4 deletions c-cpp/10_recursive/one_two_step.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ class SolutionOFOneTwoStep {
static std::unordered_map<size_t, size_t> result_;

public:
size_t operator()(size_t steps) {
enum class POLICY {
RECURSIVE,
NONRECURSIVE
};

private:
size_t recursive(size_t steps) {
auto iter = result_.find(steps);
if (result_.end() != iter) { // found.
return iter->second;
Expand All @@ -16,12 +22,50 @@ class SolutionOFOneTwoStep {
return res;
}
}
size_t nonrecursive(size_t steps) {
auto iter = result_.find(steps);
if (result_.end() != iter) { // found.
return iter->second;
} else {
size_t start;
for (start = steps; start != 2 and result_.end() == result_.find(start); --start) {}
for (size_t i = start; i != steps; ++i) {
result_.insert({i + 1, result_[i - 1] + result_[i]});
}
return result_[steps];
}
}

public:
size_t operator()(size_t steps, const POLICY policy = POLICY::RECURSIVE) {
if (policy == POLICY::RECURSIVE) {
return recursive(steps);
} else if (policy == POLICY::NONRECURSIVE) {
return nonrecursive(steps);
}
}
static void debug() {
for (auto kv : result_) {
std::cout << kv.first << ' ' << kv.second << std::endl;
}
std::cout << std::endl;
}
};

std::unordered_map<size_t, size_t>
SolutionOFOneTwoStep::result_ = {{1, 1}, {2, 2}};
std::unordered_map<size_t, size_t> SolutionOFOneTwoStep::result_ = {{1, 1}, {2, 2}};

int main() {
std::cout << SolutionOFOneTwoStep()(10) << std::endl;
SolutionOFOneTwoStep::debug();

std::cout << SolutionOFOneTwoStep()(5, SolutionOFOneTwoStep::POLICY::RECURSIVE) << std::endl;
SolutionOFOneTwoStep::debug();

std::cout << SolutionOFOneTwoStep()(10, SolutionOFOneTwoStep::POLICY::NONRECURSIVE) << std::endl;
SolutionOFOneTwoStep::debug();

std::cout << SolutionOFOneTwoStep()(20, SolutionOFOneTwoStep::POLICY::RECURSIVE) << std::endl;
SolutionOFOneTwoStep::debug();

return 0;
}

0 comments on commit 5a374e0

Please sign in to comment.