C++ 12ms bit operation


  • 0
    C
    //Combination
    class Solution {
    public:
    static int cmp(int a, int b)
    {
    	return a>b;
    }
    vector<vector<int>> combine(int n, int k) {
    
    	vector<vector<int>> vc;
    	vector<int> helper;
    	if (k == 0)
    		return vc;
    	vector<int> a(n);
    	for (int i = 0; i < k; i++)
    	{
    		a[i] = 1;
    		helper.push_back(i + 1);
    	}
    	vc.push_back(helper);
    	helper.clear();
    
    	for (int i = 0; i < n - 1; i++)
    	{
    		if (a[i] == 1 && a[i + 1] == 0)
    		{
    			a[i] = 0; a[i + 1] = 1;
    			sort(a.begin(), a.begin()+i, cmp);
    			for (int j = 0; j < n; j++)
    			{
    				if (a[j])
    					helper.push_back(j + 1);
    			}
    			vc.push_back(helper);
    			helper.clear();
    			i = -1;
    		}
    	}
    	return vc;
    }
    };

Log in to reply
 

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