LC 967. Numbers With Same Consecutive Differences
2024-10-06 23:44:05
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 except for the number 0
itself. For example, 01
has one leading zero and is invalid, but 0
is valid.
You may return the answer in any order.
Example 1:
Input: N = 3, K = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.
Example 2:
Input: N = 2, K = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
Note:
1 <= N <= 9
0 <= K <= 9
搜索题。两边搜索。注意N=1的特别情况,这个时候都行。
class Solution {
private:
unordered_map<int,vector<int>> mp ;
public:
vector<int> numsSameConsecDiff(int N, int K) { if(N == ){
vector<int> ret;
for(int i=; i<; i++) ret.push_back(i);
return ret;
}
for(int i=; i<; i++){
int idx = i + K;
if(idx < ) mp[i].push_back(idx);
idx = i - K;
if(!mp[i].empty() && mp[i][] == idx) continue;// K等于1特殊情况
if(idx >= ) mp[i].push_back(idx);
}
vector<int> ret;
for(int i=; i<; i++){
if(!mp.count(i)) continue;
helper(ret, N, i, );
}
return ret;
}
void helper(vector<int>& ret, int N, int start, int tmpval){
int tt = tmpval* + start;
if(to_string(tt).size() == N) {
ret.push_back(tt);
return;
}
if(!mp.count(start)) return ;
vector<int> choices = mp[start];
for(auto x : choices){
helper(ret, N, x, tt);
}
}
};
再贴一个yubowen大佬的解法
typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> PII; #define REP(i,s,t) for(int i=(s);i<(t);i++)
#define FILL(x,v) memset(x,v,sizeof(x)) const int INF = (int)1E9;
#define MAXN 100005 class Solution {
public:
int N, K;
void solve(int i, int ld, int val, VI &ans) {
if (i == N) {
ans.push_back(val);
return;
}
REP(t,,) {
int d = t == ? ld + K : ld - K;
if (K == && t == ) continue;
if ( <= d && d <= ) {
solve(i+, d, val* + d, ans);
}
}
}
vector<int> numsSameConsecDiff(int _N, int _K) {
N = _N; K = _K;
VI ans;
if (N == ) {
REP(i,,) ans.push_back(i);
return ans;
}
REP(s,,) solve(, s, s, ans);
return ans;
}
};
最新文章
- 。。。Spring框架总结(一)。。。
- Bootstrap——Jumbotron编写
- 成长记录 if语句输出 由大到小的数字
- javascript之冒泡算法
- cmder使用手册
- LInkedList集合练习
- Android屏幕图标尺寸规范
- iOS-容易造成循环引用的三种场景
- js 防止变量冲突
- python中的图像数据库PIL
- 验证二叉搜索树的golang实现
- 二叉树放置照相机 Binary Tree Cameras
- Gram格拉姆矩阵在风格迁移中的应用
- Java 虚拟机的对象创建
- laravel处理菜单保持的方法:
- 【代码笔记】iOS-json文件的使用
- frame与bounds的区别比较
- CSSREM
- XML External Entity attack/XXE攻击
- NABC for Teamproject