본문 바로가기
LeetCode

[LeetCode] 77. Combinations

by JungSeung 2024. 4. 18.
728x90

https://leetcode.com/

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

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

 

Example 2:

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.


Constraints:

  • 1 <= n <= 20
  • 1 <= k <= n

Code:

var combine = function(n, k) {
    // 결과를 저장할 배열
    const result = [];
    // 재귀 함수를 정의하여 조합을 생성
    
    function generateCombinations(start, currentCombination) {
        // k개의 원소를 선택한 경우, 결과에 추가
        if (currentCombination.length === k) {
            result.push([...currentCombination]);
            return;
        }
        // 현재 위치부터 n까지 반복
        for (let i = start; i <= n; i++) {
            // 현재 원소를 추가하고 재귀 호출
            currentCombination.push(i);
            generateCombinations(i + 1, currentCombination);
            // 백트래킹: 현재 원소를 제거하여 다른 조합을 시도
            currentCombination.pop();
        }
    }
    // 재귀 함수 호출 시작
    generateCombinations(1, []);
    // 최종 결과 반환
    return result;
};

 

Solutions Code :

var combine = function(n, k) {
    // 최종 결과를 저장할 배열
    const result = [];
    // 재귀 함수를 호출하여 조합 생성
    generateCombinations(1, n, k, [], result);
    // 최종 결과 반환
    return result;
};

// 조합을 생성하는 재귀 함수
function generateCombinations(start, n, k, combination, result) {
    // k개의 숫자를 선택한 경우, 현재 조합을 결과에 추가
    if (k === 0) {
        result.push([...combination]);
        return;
    }
    // 현재 위치부터 n까지 반복
    for (let i = start; i <= n; ++i) {
        // 현재 숫자를 조합에 추가
        combination.push(i);
        // 재귀 호출: 다음 숫자를 선택하도록 함
        generateCombinations(i + 1, n, k - 1, combination, result);
        // 백트래킹: 현재 숫자를 제거하여 다른 조합을 시도
        combination.pop();
    }
}

 

출처 : https://leetcode.com/problemset/all/

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 76. Minimum Window Substring  (0) 2024.03.26
[LeetCode] 75. Sort Colors  (0) 2024.03.20
[LeetCode] 74. Search a 2D Matrix  (1) 2024.03.15
[LeetCode] 73. Set Matrix Zeroes  (0) 2024.03.13
[LeetCode] 72. Edit Distance  (0) 2024.03.01