#Leetcode# 77. Combinations
https://leetcode.com/problems/combinations/
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
代码:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> nums;
for(int i = 1; i <= n; i ++)
nums.push_back(i);
set<vector<int>> ans;
vector<int> v;
vector<int> out;
int cnt;
for(int i = 0; i < (1 << n); i ++) {
v.clear();
out.clear();
cnt = 0;
A(i, v);
for(int j = 0; j < v.size(); j ++)
if(v[j]) cnt ++;
if(cnt == k) {
for(int j = 0; j < v.size(); j ++)
if(v[j])
out.push_back(nums[j]);
//sort(out.begin(), out.end());
ans.insert(out);
}
}
return vector<vector<int>>(ans.begin(), ans.end());
}
void A(int x, vector<int> &v) {
while(x) {
v.push_back(x % 2);
x /= 2;
}
}
};
写一会 $Leetcode$ 冷静冷静

浙公网安备 33010602011771号