topic
Pick a card (Picking cards)
link: https://ac.nowcoder.com/acm/contest/3286/D
There are N cards beef, a number written in the first xi i (1 ≤ i ≤ N) cards.
Cattle are now ready to pick a card from the card number (the number is greater than or equal to 1), so that these numbers are chosen for the average value of the card A.
Taurus would like to ask you a total of how many selection methods?
Description Input:
Input consists of two lines.
The first line of a positive integer N (1≤N≤50).
The second line of N integers xi (1≤xi ≤50).
Description Output:
output an integer, indicates the number of selection methods.
Example 1
输入
8
7 9 8 9
输出
5
说明
一共有5种挑选方法使得平均数为8:
1、选择第三张卡片
2、选择第一、二张卡片
3、选择第一、四张卡片
4、选择第一、二、三张卡片
5、选择第一、三、四张卡片
Example 2
输入
5
3 6 2 8 7 6 5 9
输出
19
dfs depth-first solution
Problem-solving ideas:
- Array in ascending order;
- Each back the number of each array, either select or not select (
list.remove(list.size() - 1);
) - When the average value for the target, and the remainder is 0, the result added to the collection.
- The result is the number of collection.
package backtracking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// https://ac.nowcoder.com/acm/contest/3286/D
public class PickupCards {
public static void main(String[] args) {
PickupCards obj = new PickupCards();
//int[] inputs = {7, 9, 8, 9};
//int target = 8;
int[] inputs = {3, 6, 2, 8, 7, 6, 5, 9};
int target = 5;
int result = obj.pickupCards(inputs, target);
System.out.println("result > " + result);
}
public int pickupCards(int[] inputs, int target) {
// check edges
if (inputs == null || inputs.length == 0) {
return 0;
}
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
Arrays.sort(inputs);
List<Integer> list = new ArrayList<Integer>();
//dfs
dfs(inputs, resultList, list, 0, target);
return resultList.size();
}
private void dfs(int[] inputs, List<List<Integer>> resultList, List<Integer> list, int start, int target) {
// exit condition
long sum = 0;
for (int item: list) {
sum += item;
}
if (list.size() != 0 && sum / list.size() == target && sum % list.size() == 0) {
System.out.println(Arrays.toString(list.toArray()));
resultList.add(new ArrayList<Integer>(list));
return;
}
if (start >= inputs.length) {
return;
}
list.add(inputs[start]);
dfs(inputs, resultList, list, start + 1, target);
list.remove(list.size() - 1);
dfs(inputs, resultList, list, start + 1, target);
}
}
Download
https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/PickupCards.java