Problem:
Find multiple numbers from 2,4,3,5,7,1,9,10, and 11
This topic is a variant of the 0 1 backpack, so it can be solved using DP.
The key of DP solution is to get the recursive formula, for this problem, the DP formula is:
J∈[1,11]
i∈[0,7]
DP[I][J] = The maximum value less than J is selected from (Arr[i], dparr[i-1][j], Arr[i] + dparr[i-1][j], arr[i]+ Dparr[i-1][j-arr[i]])
The specific code is as follows:
void Main () {dpfind (); Console.WriteLine (Dparr);} static int n = 11;static int[] arr = new int[]{2,4,3,5,7,9,10,6};static int[,] Dparr = new int[8,12];//j = 1..N, loop EAC h element in arr//dparr[i,j] = Max (Arr[i], dparr[i-1][j], Arr[i] + dparr[i-1][j], arr[i]+ Dparr[i-1][j-arr[i]]) and the MA X not gather than jstatic void Dpfind () {for (var i = 0; i < arr. Length; i++) {for (var j = 1; J <= N; j + +) {if (i = = 0) {var max = arr[i] > J 0:arr[i];dp arr[i,j] = max;results[i+ "," +j] = ma x;} else if (i > 0) {var Maxarr = new List<int> () {arr[i], Dparr[i-1,j],arr[i] + dparr[i-1,j]};if (J > Arr[i]) {Maxarr. ADD (Arr[i] + dparr[i-1,j-arr[i]]);} DPARR[I,J] = Maxlessthan (J,maxarr.toarray ());}}} Find the max element in arr where less than xstatic int Maxlessthan (int x, params int[] arr) {int s = 0;for (var i = 0;i & Lt Arr. Length; i++) {if (Arr[i] > S && arr[i] <= x) {s = Arr[i];}} return s;}
The last 1 elements of DP are DPARR[7][11] is the solution of the problem
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm exercises--DP lookups and arrays of specified numbers