题目
77. 组合 - 力扣(LeetCode)
Python
体会一下Python的高开发效率
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
from itertools import combinations
return list(combinations(range(1,n+1),k))
第二种解法如下:
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans=[]
sub_ans=[]
def fun(supply):
need=k-len(sub_ans) # 需求,还需要几个数
if need>supply: #需大于供
return
if need==0:
ans.append(sub_ans.copy())
for i in range(supply,0,-1):
sub_ans.append(i)
fun(i-1)
sub_ans.pop()
fun(n)
return ans
C++
class Solution {
public:
vector<vector<int>> combine(int n, int k)
{
vector<vector<int>> ans;
vector<int> sub_ans;
function<void(int)> fun=[&](int supply)
{
int need=k-sub_ans.size();
if( need>supply) return;
if(need==0)
{
ans.push_back(sub_ans);
return;
}
for(int i=supply;i>0;i--)
{
sub_ans.push_back(i);
fun(i-1);
sub_ans.pop_back();
}
};
fun(n);
return ans;
}
};
第二种:
class Solution {
public:
vector<vector<int>> combine(int n, int k)
{
vector<vector<int>> ans;
vector<int> sub_ans;
function<void(int)> fun=[&](int num)
{
int need=k-sub_ans.size();
if(need==0)
{
ans.push_back(sub_ans);
return;
}
if(num>need) fun(num-1); //可以不选
//选
sub_ans.push_back(num);
fun(num-1);
sub_ans.pop_back();
};
fun(n);
return ans;
}
};
C语言
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int **ans;
int *sub_ans;
int idx_ans;
int idx_sub;
void fun(int n,int k,int startIdx)
{
if(k==idx_sub)
{
//用tmp将sub_ans放到ans,直接使用sub_ans的话,值会变
//不能指向sub_ans
int *tmp=(int *)malloc(sizeof(int)*k); //tmp[k]
for(int i=0;i<k;i++) tmp[i]=sub_ans[i];
ans[idx_ans++]=tmp;
return;
}
for(int i=startIdx;i<=n;i++)
{
sub_ans[idx_sub++]=i;
fun(n,k,i+1);
idx_sub--;
}
}
int** combine(int n, int k, int* returnSize, int** returnColumnSizes)
{
ans=(int **)malloc(sizeof(int *)*200001); //ans[200001][]
sub_ans=(int *)malloc(sizeof(int)*k); //sub_ans[k]
idx_ans=0;
idx_sub=0;
fun(n,k,1);
*returnSize=idx_ans;
*returnColumnSizes=(int *)malloc(sizeof(int)*idx_ans);
for(int i=0;i<*returnSize;i++)
{
(*returnColumnSizes)[i]=k;
}
return ans;
}