Feedback on subsets solution, too slow for OJ

  • 0

    The online judge deemed this as a slow approach but I wanted inputs on the correctness of it, and possible optimizations without losing the binary conversion concept. Also this is a simpler solution to understand as compared to the sets approach.

    public class Solution {
            public List<List<Integer>> subsets(int[] nums) {
                 if(nums==null ||nums.length<1) return null;
                 int len=nums.length;
                 StringBuilder sb=new StringBuilder();
                 while(sb.length()!=nums.length) sb.append("0");
                 String zeroPad=sb.toString();
                 int ctr=0;
                 List<List<Integer>> allLevel=new ArrayList<List<Integer>>();
                 while(ctr!=Math.pow(2,len)) {
                     List<Integer> level=new ArrayList<Integer>();
                     String bin=getBinary(ctr,zeroPad);
                     for(int i=0;i<bin.length();++i) {
                         if(bin.charAt(i)==1) level.add(nums[i]);
                 return allLevel;
            private String getBinary(int num, String padder) {
                String binAbs=Integer.toBinaryString(num);
                return padder.substring(1,binAbs.length())+binAbs;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.