字节跳动笔试的一题
题目描述:
给定n个数组成的序列,其中每个元素都是0-9之间的个位数,要求从这个序列中找到k个元素,组成一个k位数,并且这k个元素在n个数中的相对顺序保持不变,问这个数最大是多少。
输入描述:
第一行: n k
第二行:依次输入n个数,用空格分割,表示这个序列。
输出描述:
得到的最大的k位数。
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
int maxx = -1;
void backtrack(vector<int> vec, int n, int m, int begin, int total) {
if (m == 0) {
if (total > maxx) maxx = total;
return;
}
for (int i = begin; i <= n - m; ++i) {
total = total*10 + vec[i];
backtrack(vec, n, m-1 , i + 1, total);
total = (total - vec[i]) / 10;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<int> rec;
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
rec.push_back(temp);
}
backtrack(rec, n, m, 0, 0);
cout << maxx << endl;
system("pause");
return 0;
}
笔试用二十分钟敲了自己的一个思路,,用了一个多小时来debug,都没弄好,交卷后用回溯,,十几分钟就通过了。不知道说啥。。