Recursion + Memoisation
\n\n# Code\n\nclass Solution {\n    int target;\n    int n;\n    Integer[][] dp;\n    public int lengthOfLongestSubsequence(List<Integer> nums, int target) {\n 
\n\n# Code\n```\nclass Solution {\n    int target;\n    int n;\n    Integer[][] dp;\n    public int lengthOfLongestSubsequence(List<Integer> nums, int target) {\n        this.target = target;\n        this.n = nums.size();\n        dp = new Integer[n + 1][target + 1];\n        int ans = solve(nums, 0, 0);\n        return (ans < 0) ? -1 : ans;\n    }\n    \n    int solve(List<Integer> nums, int i, int sum){\n         \n        if(sum > target) return Integer.MIN_VALUE;\n        \n        if(i == n && sum != target) return Integer.MIN_VALUE;\n        \n        if(sum == target) return 0;\n        \n        if(dp[i][sum] != null) return dp[i][sum];\n        \n        int inc = 1 + solve(nums, i + 1, sum + nums.get(i));\n        int not =  solve(nums, i + 1, sum);\n        int ans = Math.max(inc, not);\n        \n        return dp[i][sum] = ans;\n    }\n}\n```
['Java']