How about my solution using bit operation?


  • 0
    E
    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            for(int i=0;i< (1<<n);i++){
                int ones = 0;
                int iter = i;
                while(iter>0){
                    ones++;
                    iter &= iter-1;
                }
                if(ones == k){
                    List<Integer> list = new ArrayList<Integer>();
                    iter = i;
                    for(int bit=0;bit<32;bit++){
                        int shift = 1 << bit;
                        if((iter & shift) != 0){
                            list.add(bit+1);
                        }
                    }
                    result.add(list);
                }
            }
            return result;
        }
    }
    

  • 0
    Z

    Your solution works for O(32*2^n), therefore If n goes large for example 20, I guess you will get TLE


  • 0
    A

    @evilcoder I think the problem is that many loops are redundant since they don't contain k ones.


Log in to reply
 

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