fork download
  1. // https://stackoverflow.com/questions/78722724/find-unique-or-combination-for-given-array
  2.  
  3. import java.util.*;
  4.  
  5. class Solution {
  6. void solve(List<Integer> nums, int index, int lastIndex, int taken, int curr, Set<Integer> values) {
  7. if (taken > 0) {
  8. values.add(curr);
  9. }
  10. if (index >= nums.size()) {
  11. return;
  12. }
  13.  
  14. // Take it.
  15. if (lastIndex == -1 || nums.get(index) > nums.get(lastIndex)) {
  16. int newOrValue = curr | nums.get(index);
  17. if (!values.contains(newOrValue)) {
  18. solve(nums, index + 1, index, taken + 1, newOrValue, values);
  19. }
  20. }
  21. // Leave it
  22. solve(nums, index + 1, lastIndex, taken, curr, values);
  23. }
  24.  
  25. public List<Integer> getIncreasingSubsequenceOrValues(List<Integer> nums) {
  26. Set<Integer> values = new HashSet<>();
  27. solve(nums, 0 /* index */, -1 /* lastIndex */, 0 /* taken */, 0 /* curr */, values);
  28. return new ArrayList<>(values);
  29. }
  30. }
  31.  
  32. public class Main {
  33. static void print(List<Integer> v) {
  34. for (int el : v) {
  35. System.out.print(el + " ");
  36. }
  37. System.out.println();
  38. }
  39.  
  40. static void test(List<Integer> nums) {
  41. System.out.print("Testing for array: ");
  42. print(nums);
  43.  
  44. Solution solution = new Solution();
  45. List<Integer> result = solution.getIncreasingSubsequenceOrValues(nums);
  46.  
  47. print(result);
  48. }
  49.  
  50. public static void main(String[] args) {
  51. test(Arrays.asList(4, 2, 4, 1));
  52. test(Arrays.asList(3, 2, 4, 6));
  53. }
  54. }
  55.  
Success #stdin #stdout 0.15s 55628KB
stdin
Standard input is empty
stdout
Testing for array: 4 2 4 1 
1 2 4 6 
Testing for array: 3 2 4 6 
2 3 4 6 7