leetcode to do question notes 77 combinations

Given two integers  n and  sum k, return  [1, n] all possible  k combinations of numbers in the range.

You can return answers in  any order  .

Idea 1: Find the number of combinations directly and put each combination into the array

int** combine(int n, int k, int* returnSize, int** returnColumnSizes)
{
    int size = 0, num = 1, i;
    int * arr = (int*)malloc(sizeof(int) * k);
    assert(arr);
    for (i = 0; i < k; i++)
        *(arr + i) = i + 1;
    for (i = 0; i < k; i++)
        num = num * (n - i) / (i + 1);

    int ** c = (int**)malloc(sizeof(int*)* num);
    assert(c);
    *returnColumnSizes = (int*)malloc(sizeof(int) * num);
    assert(*returnColumnSizes);
    *returnSize = num;

    while (size < num)
    {
        *(*returnColumnSizes + size) = k;
        *(c + size) = (int*)malloc(sizeof(int) * k);
        assert(*(c + size));

        for (i = 0; i < k; i++)
            *(*(c + size) + i) = *(arr + i);
        
        for (i = k - 1; i >= 0; i--)
        {
            if (*(arr + i) < n - k + i + 1)
                break;
        }
        if (i < 0)
            break;
        else
        {
            *(arr + i++) += 1;
            for (; i < k; i++)
                *(arr + i) = *(arr + i - 1) + 1;
        }
        size++;
    }

    return c;
}

analyze:

This question is related to combinations. First, calculate the total number of combinations, violently enumerate various possible situations, then put the combinations into an array, and finally output the answer

Summarize:

This question examines the application of arrays. When actually writing, pay attention to whether the position is the largest number. If not, it needs to be rearranged.

Guess you like

Origin blog.csdn.net/si_mple_/article/details/132265767