Skip to the content.

Problem #967 (Numbers With Same Consecutive Differences | Backtracking, Breadth First Search)

Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k.

Note that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid.

You may return the answer in any order.

Example 1

Input:

n = 3, k = 7 <br/>

Output:

[181,292,707,818,929] <br/>

Explanation:

Note that 070 is not a valid number, because it has leading zeroes.

Example 2

Input:

n = 2, k = 1 <br/>

Output:

[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

Constraints

Solutions

Basic Idea

The problem asks us to return a list of values(integers) in which each value is n digits and the absolute difference of each two consecutive digits is k. If n is 3, then the values inside the Queue should be 3 digits.

Sample

n = 3, k = 4 - This means that the numbers in the list should have a length of `3` and each *two consecutive digits* of a number has an **absolute difference** of `4`. <br/>
Output: [151,159,262,373,404,484,515,595,626,737,840,848,951,959]
NOTE: If it only satisfies one then it only has 1 pair.

Example:

k = 4
x = 5, this refers to the first digit

1. k > 0 and x - k >= 0
    5 - 4 >= 0, true
    5 - 4 = 1, a pair
    
    | 5 - 1 | = 4, absolute difference = k
    
    Therefore, 1 is a pair of 5.

2. x + k < 10
    5 + 4 < 10, true
    5 + 4 = 9, a pair
    
    | 5 - 9 | = 4, absolute difference = k
    
    Therefore, 9 is a pair of 5.

Breadth First Search(Iterative)

The basic idea in an iterative BFS is to create a List where we will store the n digit numbers. We will use a for loop to loop from 1 - 9 which corresponds to the beginning of a number(num). For each iteration, we will create a Queue where we will first add(i) then process it inside a while loop. Inside the while loop we will determine all possible combination of numbers until our number reaches n digits. When the number satisfies all condition and rule, add it to te List.

Code Structure

vector<int> list;
min = pow(10, n - 1);
for(int i = 0; i < 10; i++){
    queue<int> q;
    q.push(i);
}

image ***

for(int i = 0; i < 10; i++){
    queue<int> q;
    q.push(i);
    while (!q.empty()) {
        int num = q.front();
        q.pop();
    }
}

image ***

for(int i = 0; i < 10; i++){
    queue<int> q;
    q.push(i);
    while (!q.empty()) {
        int num = q.front();
        q.pop();
        if(num >= min){
            list.push_back(num);
            continue;
        }
        int x = num % 10;
        if (k > 0 && x - k >= 0)
            q.push(num * 10 + x - k)
        if (x + k < 10)
            q.push(num * 10 + x + k)
    }

image ***

image ***

image ***

image ***

image ***

image ***

image ***

image ***

image ***

image ***

image ***

image ***

image ***

Keep doing this until i = 9. ***

Code

Complexity