The number n is divided into two groups, the number of groups is equal to the number of possible, the minimum difference

Description Title: for an array with a number n, divided into two groups, the number of groups the number of which is equal as possible (less than 1), while minimizing the number of and the difference between the two groups.

The subject using a similar 0-1 knapsack problem, ideas: the number k selected from the number i, and find all possible, and these flag with true and in Fig. (K, i, flag see code)

 1 public static void main(String[] args){
 2         int[] arr = {1 ,  2 ,  3 ,  5 ,  7 ,  8 ,  9};
 3         int n = 7;
 4         int sum = 0;
 5         for(int i:arr){
 6             sum += i;
 7         }
 8         boolean[][] flag = new boolean[n/2+1][sum/2+1];
 9         for(int i=0;i<n/2+1;i++){
10             for(int j=0;j<sum/2+1;j++){
11                 flag[i][j] = false;
12             }
13         }
14         flag[0][0] = true;
15         for(int k = 0;k<n;k++){
16             for(int i=k>n/2?n/2:k;i>=1;i--){
17                 //遍历s(k,i)
18                 for(int j=0;j<=sum/2;j++){
19                     if(j>=arr[k]&&flag[i-1][j-arr[k]]){
20                         flag[i][j] = true;
21                     }
22                 }
23             }
24         }
25         for(int i = sum/2;i>=0;i++){
26             if(flag[n/2][i]) {
27                 System.out.println(i);
28                 break;
29             }
30         }
31     }

I think the place is more difficult to understand the flag [i-1] What is the meaning of this line: Take behalf k i-1 from the number in their variety and the possible manifestation (ie there is true)

The innermost layer is circulating means: taking the various i-1 from the line and then add arr [k] i the number of make up and embodied in In Flag [i] inside.

Circulation means of the second layer: 1-i performs many rows

The outermost layer is the addend continue to fill it.

I tested a few examples, there may be omissions, please leave a message to point out, it is difficult to understand where the message can also be discussed.

Guess you like

Origin www.cnblogs.com/kevin-lee123/p/11563466.html