📜  门| GATE-CS-2000 |问题 33(1)

📅  最后修改于: 2023-12-03 15:28:41.052000             🧑  作者: Mango

GATE-CS-2000 Problem 33

This is a problem from the GATE (Graduate Aptitude Test in Engineering) exam for Computer Science in 2000. It is a programming problem that tests your understanding of recursion and dynamic programming.

Problem Statement

You are given an array A of n integers. You are also given a target sum T. Your task is to find a subsequence of A that adds up to exactly T, or report that no such subsequence exists.

Solution

The problem can be solved using dynamic programming. We define a two-dimensional table T[i][j] where T[i][j] is true if there is a subsequence of A[0:i] that adds up to exactly j, and false otherwise.

The base cases are T[0][0] = true (since the empty subsequence adds up to 0) and T[0][j] = false for j > 0 (since there are no elements in the empty subsequence).

For the recursive case, we consider two possibilities. Either we include the i-th element of A in the subsequence, or we don't. If we include it, then T[i][j] = T[i-1][j-A[i-1]] if j >= A[i-1], and false otherwise. If we don't include it, then T[i][j] = T[i-1][j]. In other words:

T[i][j] = T[i-1][j] || (j >= A[i-1] && T[i-1][j-A[i-1]])

Once we have filled in the entire table, we can find the subsequence that adds up to T by tracing back the table from T[n][T] to T[0][0]. If T[i][j] is true and T[i-1][j] is false, then we know that the i-th element of A is included in the subsequence. Otherwise, it is not included.

Here is the pseudocode for the algorithm:

function findSubsequence(A, T):
    n = length(A)
    T[0][0] = true
    for j = 1 to T:
        T[0][j] = false
    for i = 1 to n:
        for j = 0 to T:
            T[i][j] = T[i-1][j]
            if j >= A[i-1]:
                T[i][j] = T[i][j] || T[i-1][j-A[i-1]]
    if T[n][T]:
        j = T
        subsequence = []
        for i = n to 1:
            if j >= A[i-1] and T[i-1][j-A[i-1]]:
                subsequence.append(A[i-1])
                j = j - A[i-1]
        reverse(subsequence)
        return subsequence
    else:
        return None

Note that this algorithm has a worst-case time complexity of O(nT), where n is the length of A and T is the target sum. However, it can be optimized to use only O(T) space by using a one-dimensional table instead of a two-dimensional table.