Кotlin Coding Test Course, Exploring Combinations

1. What is Combination?

A combination refers to the number of ways to select a specific number of elements from a given set.
For example, the combinations of picking 2 elements from {A, B, C} are AB, AC, and BC.
Since combinations do not consider the order, {A, B} and {B, A} are regarded as the same combination.

2. Problem Definition

We will solve the following problem.

Problem Description

Given an integer array nums and an integer k,
the problem is to generate combinations by picking k elements from the nums array.
Return the combinations in the form of a list of lists.

Input Example

        nums = [1, 2, 3, 4]
        k = 2
    

Output Example

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

3. Algorithm Approach

There are several methods to generate combinations, but
the simplest and most representative method is to use backtracking.
This method explores all possible cases while
generating combinations based on basic conditions.

4. Implementation in Kotlin

Let’s implement the algorithm described earlier in Kotlin.

fun combine(nums: IntArray, k: Int): List> {
        val result = mutableListOf>()
        backtrack(result, mutableListOf(), nums, k, 0)
        return result
    }

    fun backtrack(result: MutableList>, tempList: MutableList, nums: IntArray, k: Int, start: Int) {
        // If the size of the combination is equal to k, add it to the result
        if (tempList.size == k) {
            result.add(ArrayList(tempList))
            return
        }
        // Generate combinations
        for (i in start until nums.size) {
            tempList.add(nums[i])
            backtrack(result, tempList, nums, k, i + 1)
            tempList.removeAt(tempList.size - 1)
        }
    }

    // Example usage
    fun main() {
        val nums = intArrayOf(1, 2, 3, 4)
        val k = 2
        val combinations = combine(nums, k)
        println(combinations)
    }

5. Code Explanation

The code above is structured as follows.

  • combine: The main function initializes a list to store results and a temporary list to store combinations, and calls the backtracking function.
  • backtrack: A function that recursively generates combinations. If the current combination size is equal to k, it adds to the result list; otherwise, it repeats by adding the next element.

6. Complexity Analysis

The time complexity of this algorithm is proportional to the number of combinations.
In the worst case, it has a time complexity of O(N^K),
and the space complexity is O(K).

7. Conclusion

The problem of generating combinations is frequently encountered in coding tests.
The backtracking technique can effectively solve combination generation problems.
Based on what you learned today, I hope you will practice various combination problems.