top of page
Caută
Poza scriitoruluioanaunciuleanu

Subset Sum Problem in JAVA

Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with the sum equal to the given sum.


Input: int[] numbersSet = {2, 35, 8, 10, 6, 3}; int sum = 12; Output: true Explanation: 2 + 10 = 12.




Solution:


1. static boolean isSubsetSum(int[] numbersSet, int sum) { 2. int length = numbersSet.length; 3. boolean[][] subsets = new boolean[sum + 1][length + 1]; 4. 5. for (int i = 0; i <= length; i++) { 6. subsets[0][i] = true; 7. } 8. 9. for (int i = 1; i <= sum; i++) { 10. subsets[i][0] = false; 11. } 12. 13. for (int i = 1; i <= sum; i++) { 14. for (int j = 1; j <= length; j++) { 15. subsets[i][j] = subsets[i][j - 1]; 16. if (i >= numbersSet[j - 1]) { 17. subsets[i][j] = subsets[i][j] || subsets[i - numbersSet[j - 1]][j - 1]; 18. } 19. } 20. } 21. 22. return subsets[sum][length]; 23. } 24.

7 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no...

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed...

Comments


bottom of page