Algorithm exercises--DP lookups and arrays of specified numbers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.