给定数字N ,任务是打印前N个步进编号。
A number is called stepping number if all adjacent digits have an absolute difference of 1. For e.g. 321 is a Stepping Number while 421 is not.
例子:
Input: N = 7
Output: 1, 2, 3, 4, 5, 6, 7
Input: N = 14
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22
幼稚的方法:我们可以从1开始,检查每个数字是否为Stepping编号,然后继续直到找到第K个Stepping编号。
高效方法:
- 生成所有可能的步进数,直到1000,以便于计算
- 对于N的每个值,只需打印已计算的N个步进数即可
下面是上述方法的实现:
C++
// C++ Program to print first N
// Stepping numbers
#include
using namespace std;
// Function to generate
// the Stepping numbers
void generateSteppingNos(
int x, set& s)
{
if (x > 1e8)
return;
// Inserting the current
// element in the set
s.insert(x);
// Retrieving the last digit
// of the current number
int last = x % 10;
if (last - 1 >= 0)
// Appending x-1 to
// the current number
generateSteppingNos(
x * 10 + last - 1,
s);
// Appending x to
// the current number
generateSteppingNos(
x * 10 + last,
s);
if (last + 1 <= 9)
// Appending x+1 to
// the current number
generateSteppingNos(
x * 10 + last + 1,
s);
}
// Function to print
// N Stepping numbers
void NSteppingNumbers(int N)
{
set s;
for (int i = 1; i <= 9; i++)
generateSteppingNos(i, s);
int count = 1;
// Printing N numbers from s
for (auto& it : s) {
if (count <= N) {
cout << it << ", ";
count++;
}
else
break;
}
}
// Driver code
int main()
{
int N = 14;
NSteppingNumbers(N);
return 0;
}
Python3
# Python3 Program to print first N
# Stepping numbers
# Function to generate
# the Stepping numbers
def generateSteppingNos(x, s):
if (x > 1e8):
return
# Inserting the current
# element in the set
s.add(x)
# Retrieving the last digit
# of the current number
last = x % 10
if (last - 1 >= 0):
# Appending x-1 to
# the current number
generateSteppingNos(x * 10 + last - 1, s)
# Appending x to
# the current number
generateSteppingNos(x * 10 + last, s)
if (last + 1 <= 9):
# Appending x+1 to
# the current number
generateSteppingNos(x * 10 + last + 1, s)
# Function to print
# N Stepping numbers
def NSteppingNumbers(N):
s = set()
for i in range(1, 10):
generateSteppingNos(i, s)
count = 1
s.pop()
# Printing N numbers from s
for value in s:
if (count <= N):
print(value, end=', ')
count = count + 1
else:
break
# Driver code
N = 14
NSteppingNumbers(N)
# This code is contributed by Sanjit_Prasad
输出:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22,