967. Numbers With Same Consecutive Differences
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { vector<int> res; void dfs(int n, int k, int c) { if(!n) { res.push_back(c); return; } int nextLessDigit = c % 10 - k, nextGreaterDigit = c % 10 + k; if(0 <= nextGreaterDigit and nextGreaterDigit <= 9) dfs(n-1,k,c*10 + nextGreaterDigit); if(0 <= nextLessDigit and nextLessDigit <= 9) dfs(n-1,k,c*10 + nextLessDigit); } public: vector<int> numsSameConsecDiff(int n, int k) { for(int i = 1; i <= 9; i++) { dfs(n-1, k ,i); }
return res; } };
|