Here is a dynamic programming solution to solve the subset sum problem in R:
625 chars33 lines
The function subset_sum takes an input array arr, n which is the length of the array, and a sum which is the target sum that we need to find in the array. It returns a boolean value, TRUE if a subset with sum equals to sum exists, otherwise FALSE.
The algorithm works by creating a matrix dp of size (n+1) x (sum+1) where dp[i][j] represents whether the target sum j can be achieved by a subset of the first i elements of arr.
The base case of the algorithm is that a sum of 0 can always be achieved by an empty subset. For recursive cases, we first check whether the i-th element of arr is greater than the target sum j. If it is, it's impossible to form a subset that adds up to j using that element alone. So, we just copy the result for the previous row in the dp matrix. If the i-th element of arr is less than or equal to the sum j, we have two choices - either include it in the subset or exclude it. If we include it, we need to find a subset in the previous row that adds up to j-arr[i-1]. If we exclude it, we need to find a subset that adds up to j in the previous row. So, we take logical OR of these 2 possibilities and store the result in the current cell of the dp matrix.
Finally, we return dp[n+1][sum+1] as TRUE or FALSE depending on whether the target sum sum can be achieved by a subset of arr.
gistlibby LogSnag