Simple Java bit manipulation solution : 3ms


  • 0
    R

    The idea is to iterate the bit till n bits are set to one. "n" is the length of the array. helper function returns which index to set for each iteration. Simple and self-explanatory code. Any improvements are welcomed.

    public class Solution {
      		public List<List<Integer>> subsets(int[] nums) {
    		List<List<Integer>> list1 = new ArrayList<>();
    		list1.add(new ArrayList<Integer>());
    		int bit = 1;
    		int pow = (int) Math.pow(2, nums.length);
    		for (int i = 0; i < pow - 1; i++) {
    			List<Integer> index = positionOfBit(bit);
    			List<Integer> res = new ArrayList<>();
    			for (int j = 0; j < index.size(); j++) {
    				res.add(nums[index.get(j)]);
    			}
    			list1.add(res);
    			bit++;
    		}
    		return list1;
    	}
    
    
    	private List<Integer> positionOfBit(int b) {
    		int index = 0, c = 1;
    		List<Integer> res = new ArrayList<>();
    		while (b > 0) {
    			if ((b & c) != 0) {
    				res.add(index);
    			}
    			index++;
    			b = b >> 1;
    		}
    		return res;
    	}
    }
    

Log in to reply
 

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