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);
}
}
}
@hsaputra
Copy link
Author

hsaputra commented Oct 4, 2018

Subsets II - No DUplicate

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result= new ArrayList<>();
        dfs(nums, 0, new ArrayList<Integer>(), result);
        return result;
    }
    
    private void dfs(int[] nums, int index, List<Integer> path, List<List<Integer>> result) {
        // stopping criteria
        if (index > nums.length) {
          return;
        }
        result.add(path);

        for(int i = index; i < nums.length; i++) {
            // Check duplicate
            if( i > index && nums[i]==nums[i-1]) {
                continue;
            }
            
            List<Integer> nPath= new ArrayList<>(path);
            nPath.add(nums[i]);
            
            dfs(nums, i+1, nPath, result);
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment