Nice and elegant bit manipulation solutions in Python and Java


  • 0
    F
    public class Solution{
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> ans = new ArrayList<List<Integer>>();
            for (int i = 0; i <= (1 << nums.length) - 1; i++) {
                int num = i;
                List<Integer> tmp = new ArrayList<Integer>();
                for (int j = 0; j <= nums.length; j++) {
                    if ((num & 1) == 1) {
                        tmp.add(nums[j]);
                    }
                    num >>= 1;
                }
                ans.add(tmp);
            }
            return ans;
        }
    }
    
    class Solution(object):
        def subsets(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            ans = []
            for flip in range(1 << len(nums)):
                tmp = []
                for i in range(len(nums)):
                    if flip & 1:
                        tmp.append(nums[i])
                    flip >>= 1
                ans.append(tmp)
            return ans
    

Log in to reply
 

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