exercise

6.1

a)

b)

6.3

a)
A(n):
	if(n<=4)return n
	return A(n-1)+A(n-3)+2*A(n-4)
b)

Let T(n) be calls made by REC-A(n). For n≥5, . Thus with .

Another approach

c)
M[1...n] initialized with -1
M[1]=1; M[2]=2; M[3]=3; M[4]=4;
MEMO-A(n, M):
 if M[n]!=-1 return M[n]
 M[n] <- MEMO-A(n-1,M) + MEMO-A(n-3,M) + 2*MEMO-A(n-4,M)
 return M[n]

Time With memorization one compute ​ for each exactly once, which gives

d)
  1. DP table: one array DP[1..n]. DP[i] = A_i.
  2. Entry formula:
  3. Base cases: DP[1]=1, DP[2]=2, DP[3]=3, DP[4]=4.
  4. For i≥5: DP[i] = DP[i-1] + DP[i-3] + 2*DP[i-4].
  5. Order: increasing i = 5…n.
  6. Extracting solution: return DP[n].
  7. Run time: pseudo code:
A(n):
	array A[1...n]
	if(n<=4)return n
	for i <- 5...n:
 A[i] <- A[i-1]+A[i-3]+2*A[i-4]
	return A[n]

6.4

a)

, , with The output of algorithm 1:

b)

explanation: The outer loop runs for to n (n iterations). For each , the inner loop scans all coin types and does work per coin. In total, we get

c)

IH: in the algorithm gives Base: this is true because if the total value is 0, then we need no coins IS: Assume are already computed. We can then obtain the best choosing strategy () by selecting one coin and a optimal choosing strategy from (which is determined by the coin we chose). The algorithm iterate through all possible coins and finds the choosing strategy with least coins. Thus, after each outer iteration, must have the value of

d)
array f[0...n] <- undefined
f[0] <- 0
findOPT(n):
	if f[n] is undefined then
 return f[n]
	best <- INF
	for i <- 1...k do
 if b[i]<=n then
 best <- min(best, 1 + findOPT(n − b[i]))
	f[n] <- best
	return f[n]

Print(findOPT(N))