Leetcode 77. 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],]

分析

基本的组合问题,可以使用递归或回溯等算法。
我使用的是递增,比如12-13-14-23-24-34,从后面依次递增到最大的n,如果到达最大,就找到之前的一位增加,这时之后的数字需要依次递增。例如145-234
此处需要带上型号,否则 (*columnSizes)[i]=k;就会报错,内存对齐问题,找这个bug找了好久才找到。。。

/**
 * 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().
 */
int** combine(int n, int k, int** columnSizes, int* returnSize) {
    int n1=n,k1=k;
    if(n1=1)
    {
        temp1=temp1*n1;
        n1--;
        temp2=temp2*k1;
        k1--;
    }
    *returnSize=temp1/temp2;
    int ** ans=(int**)malloc(sizeof(int *)*(*returnSize));
    *columnSizes=(int *)malloc(sizeof(int)*(*returnSize));
    for(int i=0;i<(*returnSize);i++)
    {
        ans[i]=(int *)malloc(sizeof(int)*k);
        for(int j=0;j=n+p-k+1&&p>=0)
            p--;
        if(p==k-1)
        {
            ans[i+1][p]=ans[i+1][p]+1;
        }
        else if(p>=0)
        {
            ans[i+1][p]=ans[i+1][p]+1;
            for(int j=p+1;j

你可能感兴趣的:(Leetcode 77. Combinations)