[leetcode]77. 组合

1.题目:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

2.代码:

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
#define MAX 10000
/*
模拟手动找出的过程;
相当于树的深度遍历,depth为深度,即当前要存放的位置;
s作为暂时存放的数组,一直都是哪一个;
*/

void dfs(int **r,int *s,int n,int k,int depth,int start,int* returnSize){
    if(depth==k){        //为k即超出了,赋值
        r[*returnSize]=(int *)malloc(sizeof(int )*k);       
        memcpy(r[*returnSize],s,sizeof(int)*k);      
        (*returnSize)++;    
        return;
    }
    for(int i=start;i<n;i++){
        s[depth]=i+1;	 //i+1保证从1开始
        dfs(r,s,n,k,depth+1,i+1,returnSize);
    }
}

int** combine(int n, int k, int** columnSizes, int* returnSize) {
    int **r=(int **)malloc(sizeof(int *)*MAX);
    int *s=(int *)malloc(sizeof(int )*k);
    *returnSize=0;
    dfs(r,s,n,k,0,0,returnSize);
    *columnSizes=malloc(sizeof(int )*(*returnSize));
    for(int i=0;i<*returnSize;i++){
        (*columnSizes)[i]=k;
    }
    return r;
}

3.知识点:

回溯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值