JAVA(1ms) and Python(49ms) Solution -- bit manipulation


  • 0
    K
    //JAVA
    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> result = new ArrayList<>();
            int n = nums.length;
            for (int i = 0;i<(1<<n);i++){   //1<<n : 2^n
                List<Integer> subset = new ArrayList<>();
                for (int j=0;j<n;j++){
                    if ((i&(1<<j))!=0){   //i&(1<<j) : i.get(j) 
                        subset.add(nums[j]);
                    }
                }
                result.add(subset);
            }
            return result;
        }
    }
    #python
    class Solution(object):
        def subsets(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            result = []
            n = len(nums)
            for i in range (1<<n):  #1<<n : 2^n
                subset = []
                for j in range (n):
                    if (i & 1<<j) != 0:  # i & 1<<j : i.get(j)
                        subset.append(nums[j])
                result.append(subset)
            return result

Log in to reply
 

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