华为OD题目:组装新的数组
知识点回溯数组
时间限制: 1s 空间限制: 256MB 限定语言: 不限
题目描述:
给你一个整数M和数组N,N中的元素为连续整数,,要求根据N中的元素组装成新的数组R,组装规则:
1.R中元素总和加起来等于M
2.R中的元素可以从N中重复选取
3.R中的元素最多只能有1个不在N中,且比N中的数字都要小 (不能为负数)
请输出: 数组R一共有多少组装办法
输入描述:
第一行输入是连续数组N,采用空格分隔
第二行输入数字M
输出描述:
输出的是组装办法数量,int类型
补充说明:
1 <= N.length <= 30
1 <= N.length <= 1000
示例1
输入:
0
5
输出:
1
说明:
只有1种组装办法,就是[2,2,1]
示例2
输入:
2 3
5
输出:
2
说明:
共2种组装办法,分别是[2,2,1],[2,3]
2 3 4
5
解题思路:
- 回溯
- 注意在递归出口那里判断要注意
- 不能是小于等于,要不然等于的话,会有多余的出来
- 比如: 最小值是2 最大值是4,如果是小于等于的话, 2 2 2和2 2 2 2都可以,这样是不符合条件的
public class My {
public static int total = 0;
public static int min = 0;
public static int max = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] strings = str.split(" ");
String line = sc.nextLine();
int n = Integer.parseInt(line);
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
min = array[0];
max = array[array.length - 1];
dfs(array, 0, n);
System.out.println(total);
}
public static void dfs(int[] array,int index, int remain) {
/*
剩下的小于最小数就可以组装,记得这里不能是小于等于,要不然等于的话,会有多余的出来
比如: 最小值是2 最大值是4,如果是小于等于的话, 2 2 2和2 2 2 2都可以,这样是不符合条件的
*/
if (remain < min) {
total++;
return;
}
for (int i = index; i < array.length; i++) {
int val = array[i];
if (val > remain) {
break;
}
remain -= val;
dfs(array, i, remain);
//下面是回溯
remain += val;
}
}
}