My solution based on enumeration of bits


  • 0
    D

    based on https://www.topcoder.com/blog/generating-combinations/

    public class Solution {
        public List<List<Integer>> combine(int n, int r) {
            
            List<List<Integer>> ls = new ArrayList<>();
            
            for(int i=0; i<(1<<n);i++){
                if(Integer.bitCount(i)==r){
                    // System.out.println("--> "+ i );
                    List<Integer> temp = new ArrayList<>();
                    // temp.add(i);
                    for(int j=0;j<32;j++){
                        // System.out.println("j>> "+ j);
                        if((i & (1<<j)) != 0 ){
                            // System.out.println("Bit is set at " + (j));
                            temp.add(j+1);
                        }
                    }
                    ls.add(temp);
                }
            }
            return ls;
            
        }
    }
    
    

    I am unsure if this will always give the correct answer for all combinations as currently, I iterate through only 32 bits for integer.


Log in to reply
 

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