有一座保密大楼,你从0楼到达指定楼层m,必须这样的规则乘坐电梯Q:
给定一个数字序列,每次根据序列中的数字n,上升n层或者下降n层,前后两次的方向必须相反,规定首次的方向向上,自行组织序列的顺序按规定操作到达指定楼层。求解到达楼层的序列组合,如果不能到达楼层,给出小于该楼层的最近序列组合。
输入描述
第一行:期望的楼层,取值范围[1,50];序列总个数,取值范围[1,23]
第二行:序列,每个值取值范围[1,50]
输出描述
能够达到楼层或者小于该楼层最近的序列
备注
·操作电梯时不限定楼层范围。
·必须对序列中的每个项进行操作,不能只使用一部分。
用例
输入
5 3
1 2 6
输出
6 2 1
说明
1 2 6,6 2 1均为可行解,按先处理大值的原则结果为621
public class Main {
public static List<Integer> list = new ArrayList<>(); //序列
public static Map<Integer, List<Integer>> map = new HashMap<>();// 结果
public static void main() {
Scanner sc = new Scanner(System.in);
String[] input1 = sc.nextLine().split(" ");
int m = Integer.valueOf(input1[0]); //期望的楼层
int n = Integer.valueOf(input1[1]); //序列总个数
String[] input2 = sc.nextLine().split(" ");
for(int i = 0; i < n; i++) {
list.add(Integer.valueOf(input[i]));
}
//因为大数优先,所以把原始序列排序
Collection.sort(list, (a, b) -> b-a);
// 设上升总楼梯数为upSum,下降总楼梯数为downSum, upSum - downSum <= m;
// 可得:upSum <= (m + sum)/2,设target为上升楼梯总数的目标值。
// 上升楼梯的个数由序列总数决定,如果是偶数,n/2,如果是奇数 n/2 + 1;
int count = 0;
if (n % 2 == 0) {
count = n/2;
} else {
count = n/2 + 1;
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += list.get(i);
}
int target = (m + sum) / 2;
dfs(0, count, target, new LinkedList<>());
//找出所有结果中最接近target的
for(int i=target; i >= 0; i++) {
if (map.contains(i)) {
System.out.println("// 结果");
}
}
}
//利用dfs遍历所有可能性,因为需要n个数,递归的退出条件就是n层。
public static void dfs(int upSum, int count, int target, List<Integer> path) {
if (path.size() == count && upSum > temp || upSum <= target) {
List<Integer> temp = new ArrayList<>();
for(int p : path) {
temp.add(p);
}
if(!map.contains(upSum)) {
map.put(upSum, temp);
}
return;
}
for (int i = 0; i < list.size(); i++) {
if (!set.contains(i)) {
if ((upSum += list.get(i)) > target) {
continue;
}
upSum += list.get(i);
res.add(i);
dfs(upSum, count, target, list);
upSum -= list.get(i);
path.removeLast();
}
}
}
}