跳房子,也叫跳飞机,是一种世界性的儿童游戏
游戏参与者需要分多个回合按顺序跳到第1格直到房子的最后一格。
跳房子的过程中,可以向前跳,也可以向后跳。
假设房子的总格数是count,小红每回合可能连续跳的步教都放在数组steps中,请问数组中是否有一种步数的组合,可以让小红两个回合跳到量后一格?如果有,请输出索引和最小的步数组合.
注意:
数组中的步数可以重复,但数组中的元素不能重复使用
。提供的数据保证存在满足题目要求的组合,且索引和最小的步数组合是唯一的
输入描述
第一行输入为房子总格数count,它是int整数类型。
第二行输入为每回合可能连续跳的步数,它是int整数数组类型
输出描述
返回索引和最小的满足要求的步数组合(顺序保持steps中原有顺序
备注
count ≤ 1000
0 ≤ steps.length ≤ 5000
-100000000 ≤steps ≤ 100000000
示例1:
输入
[1,4,5,2,2]
7
输出
[5,2]
示例2:
输入
[-1,2,4,9,6]
8
输出
[-1,9]
说明:此样例有多种组合满足两回合跳到最后,譬如: [-1,9],[2,6],其中[-1,9]的索引和为0+3=3,[2,6]的索和为1+4=5,所以索引和最小的步数组合[-1,9]
注:是满足两步跳到目标位置,也可以用两个循环判断,map来存储下标和,最后输出最小的和即可。判断1~n步以上都可以用下面这个方法。
java代码
package odTest;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class skipHouse {
static int minIndexCom = 0;
static String IndexStrCom = "";
static int currentSum = 0;
static int count = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().replace("[", "").replace("]", "").split(",");
int[] inputInts = Arrays.stream(input).mapToInt(Integer::parseInt).toArray();
int step = Integer.parseInt(scanner.nextLine());
boolean[] hasUsed = new boolean[inputInts.length];
Arrays.fill(hasUsed, false);
judgeMean(inputInts,hasUsed,step,0,"");
int[] res = Arrays.stream(IndexStrCom.split(" ")).mapToInt(Integer::parseInt).toArray();
System.out.print("[");
for(int i = 0;i<res.length;i++) {
System.out.print(inputInts[res[i]]);
if(i+1!=res.length) {
System.out.print(",");
}
}
System.out.print("]");
}
private static void judgeMean(int[] inputInts, boolean[] hasUsed, int step,int currentIndexSum,String currentIndexStr) {
if(currentSum == step&& count<3) {
if(minIndexCom ==0 ) {
minIndexCom = currentIndexSum;
IndexStrCom = currentIndexStr;
}else if(currentIndexSum<minIndexCom) {
minIndexCom = currentIndexSum;
IndexStrCom = currentIndexStr;
}
return;
}
if(currentSum>step) {
return;
}
for(int i=0;i<inputInts.length;i++) {
if(hasUsed[i]) {
continue;
}
count = count+1;
currentSum = currentSum+inputInts[i];
hasUsed[i] = true;
currentIndexSum = currentIndexSum+i;
currentIndexStr = currentIndexStr+i+" ";
judgeMean(inputInts,hasUsed,step,currentIndexSum,currentIndexStr);
currentSum = currentSum - inputInts[i];
currentIndexSum = currentIndexSum-i;
currentIndexStr=currentIndexStr.replace(i+" ", "");
hasUsed[i] = false;
count = count -1;
}
}
}