题目描述
跳房子,也叫跳飞机,是一种世界性的儿童游戏。游戏参与者需要分多个回合按顺序跳到第1格直到房子的最后一格。跳房子的过程中,可以向前跳,也可以向后跳。
假设房子的总格数是 count,小红每回合可能连续跳的步教都放在数组stepS 中,请问数组中是否有一种步数的组合,可以让小红两个回合跳到量后一格?
如果有,请输出索引和最小的步数组合。
注意:
数组中的步数可以重复,但数组中的元素不能重复使用。
提供的数据保证存在满足题目要求的组合,且索引和最小的步数组合是唯一的。
输入描述
第一行输入为房子总格数 COunt,它是 int 整数类型
第二行输入为每回合可能连续跳的步数,它是 int 整数数组类型。
输出描述
返回满足要求的索引和最小的步数组合(顺序保持 steps 中原有顺序)
补充说明
count ≤ 1000, 0 ≤ steps.length ≤5000, -100000000 ≤ steps ≤ 100000000
示例1:
输入:
8
[-1,2,4,9,6]
输出
[-1,9]
备注:此样例有多种组合满足两回合跳到最后,譬如:[-1,9],[2,6],其中[-1.9]阳的索引和为 0+3=3,[2,6]的索和为1+4=5,所以索引和最小的步数组合[-1,9]
示例2:
输入:
7
[1,4,5,2,2]
输出
[5,2]
参考C++代码
#include <bits/stdc++.h>
using namespace std;
void StepHouse(vector<int> &res, int count, vector<int> steps)
{
int sum = INT_MAX;
int l = 0, r = 0;
for (int i = 0; i < steps.size(); ++i) {
for (int j = i + 1; j < steps.size(); ++j) {
if (i + j >= sum) {
break;
}
if (steps[i] + steps[j] == count) {
sum = i + j;
res[0] = steps[i];
res[1] = steps[j];
}
}
}
}
int main()
{
int count;
cin >> count;
vector<int> arr;
vector<int>res(2);
int n = 0;
while (cin >> n) {
arr.emplace_back(n);
if (cin.get() == '\n') break;// 遇到回车后停止输入
}
StepHouse(res, count, arr);
cout << "[" << res[0] << ", " << res[1] << "]"<< endl;
return 0;
}