problems(cpp): add „967. Numbers With Same Consecutive Differences“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-09-03 23:52:07 +02:00
parent 227124b327
commit b9d382731b
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,74 @@
#include <vector>
namespace {
void nums_same_consec_diff(int n, int k, std::vector<int>& nums, int number)
{
if (n == 0) {
nums.push_back(number);
return;
}
auto last_digit = number % 10;
for (int d = 0; d < 10; d++) {
if (std::abs(last_digit - d) == k) {
nums_same_consec_diff(n - 1, k, nums, number * 10 + d);
}
}
}
}
class Solution {
public:
std::vector<int> numsSameConsecDiff(int n, int k)
{
std::vector<int> nums;
for (int d = 1; d < 10; d++) {
nums_same_consec_diff(n - 1, k, nums, d);
}
return nums;
}
};
#pragma region tests
#include <gtest/gtest.h>
TEST(examples, first)
{
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(3, 7), (std::vector { 181, 292, 707, 818, 929 }));
}
TEST(examples, second)
{
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(2, 1),
(std::vector { 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78,
87, 89, 98 }));
}
TEST(same, two)
{
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(2, 0),
(std::vector { 11, 22, 33, 44, 55, 66, 77, 88, 99 }));
}
TEST(same, three)
{
Solution s;
ASSERT_EQ(s.numsSameConsecDiff(3, 0),
(std::vector { 111, 222, 333, 444, 555, 666, 777, 888, 999 }));
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#pragma endregion /* tests */