# Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,

If n = 4 and k = 2, a solution is:

[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

# 方法一：

class Solution {
public:
vector<vector<int>> res;
vector<int> part;
void com(int dep,int maxdep,int n,int start)
{
if(dep==maxdep)
{
res.push_back(part);
return;
}
for(int i=start;i<=n;i++)
{
part[dep]=i;
com(dep+1,maxdep,n,i+1);
}
}
vector<vector<int>> combine(int n, int k) {
if(n<1) return res;
part.resize(k);
if(k==0||k==n)
{
part.resize(n);
for(int i=1;i<=n;i++)
part[i-1]=i;
res.push_back(part);
return res;
}
com(0,k,n,1);
return res;
}
};

# 方法二：

class Solution {
public:
int int_to_bool(int n,vector<int>&index)//返回1出现的次数，也就是组合中元素的个数
{
int len=index.size();
index.clear();
index.resize(len);
int i=0;
while(n)
{
int temp=n%2;
index[i]=temp;
if(temp==1)
i++;
n/=2;
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
if(n<1) return res;
vector<int> num;
for(int i=1;i<=n;i++)
num.push_back(i);
if(k==0||k==n)
{
res.push_back(num);
return res;
}
vector<int> index(n,0);
for(int i=0;i<(1<<n);i++)
{
if(int_to_bool(i,index)==k)
{
vector<int> temp;
for(int j=0;j<n;j++)
{
if(index[j]==1)
temp.push_back(num[j]);
}
res.push_back(temp);
}
}
return res;
}
};

#### Python使用combinations实现排列组合

2017-07-30 17:25:14

#### <LeetCode OJ> 77. Combinations

2016-03-09 15:35:14

#### 77 Combinations

2015-10-25 16:20:02

#### leetcode 77. Combinations-排列|递归|非递归|Java|Python

2016-06-02 10:43:01

#### LeetCode 17 Letter Combinations of a Phone Number(C,C++,Java,Python)

2015-05-10 13:39:32

#### LeetCode 77 Combinations (Python详解及实现)

2017-08-08 13:50:46

#### 【LEETCODE】77-Combinations [Python]

2016-01-07 16:57:28

#### 【LeetCode】Combinations 解题报告

2014-12-07 15:38:18

#### (Java）LeetCode-17. Letter Combinations of a Phone Number

2016-05-29 22:35:46

#### [leetcode] 17. Letter Combinations of a Phone Number ,python实现【medium】

2016-06-14 22:25:54