A bit mask solution


  • -1
    L

    Algo: brout-force enumeration + bit operation.
    Note: It doesn't fit large n but small k. Admin can add this type of test case.

    class Solution {
    public:
        vector<vector<int> > combine(int n, int k) {
            vector< vector<int> > ans;
    		for (int mask = 0; mask < (1 << n); ++mask) {
    			int cnt = 0;
    			for (int j = 0; j < n; ++j) if (mask & (1 << j)) ++cnt;
    			if (cnt == k) {
    				vector<int> tmp;
    				for (int j = 0; j < n; ++j) if (mask & (1 << j)) {
    					tmp.push_back(j + 1);
    				}
    				ans.push_back(move(tmp));
    			}
    		}
    		return ans;
        }
    };

Log in to reply
 

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