Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Created October 3, 2018 20:51
Show Gist options
  • Save hsaputra/074d4a0c1b302a389232901f4aa978a3 to your computer and use it in GitHub Desktop.
Save hsaputra/074d4a0c1b302a389232901f4aa978a3 to your computer and use it in GitHub Desktop.
class Solution {
public List<List<Integer>> subsets(int[] nums) {
// check
if (nums == null) {
throw new IllegalArgumentException();
}
List<List<Integer>> results = new LinkedList<List<Integer>>();
// prepare to recursive
List<Integer> prefix = new LinkedList<Integer>();
// lets recursive to process all
recursiveSubset(nums, 0, prefix, results);
return results;
}
private void recursiveSubset(int[] nums, int index, List<Integer> prefix, List<List<Integer>> results) {
// stopping criteria
if (index > nums.length) {
return;
}
// Process the prefix b4 we modify
results.add(new LinkedList<Integer>(prefix));
for (int i = index; i < nums.length; i++) {
int curNum = nums[i];
prefix.add(curNum);
recursiveSubset(nums, i + 1, prefix, results);
// remove last prefix;
prefix.remove(prefix.size() - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment