#Leetcode# 77. Combinations
Posted 丧心病狂工科女
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#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; } } };
看 FH 的链表看的有点绕 写一会 $Leetcode$ 冷静冷静
以上是关于#Leetcode# 77. Combinations的主要内容,如果未能解决你的问题,请参考以下文章