Iterative DP
Code


# Code
```cpp []
class Solution {
public:
    int lengthOfLongestSubsequence(vector<int>& nums, int target) {
        // dp[i][target][0] = Length of longest subsequence with sum equal to target ending at index i if we dont include this element

// dp[i][target][1] = Length of longest subsequence with sum equal to target ending at index i if we include this element


// dp[i][target][0] = max(dp[i - 1][target][0], dp[i - 1][target][1])

// dp[i][target][1] = max(dp[i - 1][target - nums[i]][0], dp[i - 1][target - nums[i]][1])
        int n = nums.size();
        int maximum = max(*max_element(nums.begin(), nums.end()), target);
        int dp[n][maximum + 1][2];
        memset(dp, 0, sizeof(dp));
        dp[0][nums[0]][1] = 1;
        int ans = 0;
        if(nums[0] == target) ans = 1;
        for(int i = 1; i < n; i++) {
            for(int j = 1; j <= target; j++) {
                dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j][1]);
                if(j - nums[i] > 0) {
                    if(dp[i - 1][j - nums[i]][0] > 0) {
                        dp[i][j][1] = max(dp[i][j][1], 1 + dp[i - 1][j - nums[i]][0]);
                    }
                    if(dp[i - 1][j - nums[i]][1] > 0) {
                        dp[i][j][1] = max(dp[i][j][1], 1 + dp[i - 1][j - nums[i]][1]);
                    }
                }
                if(j - nums[i] == 0) dp[i][j][1] = 1;
                if(j == target) ans = max(ans, max(dp[i][j][1], dp[i][j][0]));
            }
        }
        return ans == 0 ? -1 : ans;
    }
};


```
['C++']