forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
50 lines (37 loc) · 1.02 KB
/
main.cpp
File metadata and controls
50 lines (37 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// Source : https://leetcode.com/problems/numbers-with-same-consecutive-differences/
/// Author : liuyubobobo
/// Time : 2019-03-17
#include <iostream>
#include <vector>
using namespace std;
/// Backtrack
/// Time Complexity: O(2^N)
/// Space Complexity: O(N)
class Solution {
public:
vector<int> numsSameConsecDiff(int N, int K) {
vector<int> num(N, -1);
vector<int> res;
for(int i = 0 + (N != 1); i <= 9; i ++)
dfs(num, 0, i, K, res);
return res;
}
private:
void dfs(vector<int>& num, int pos, int digit, int K, vector<int>& res){
num[pos] = digit;
if(pos == num.size() - 1){
res.push_back(get_num(num));
return;
}
if(digit - K >= 0) dfs(num, pos + 1, digit - K, K, res);
if(digit + K <= 9 && K) dfs(num, pos + 1, digit + K, K, res);
}
int get_num(const vector<int>& num){
int ret = 0;
for(int e: num) ret = ret * 10 + e;
return ret;
}
};
int main() {
return 0;
}