LintCode 1464:The K-th Combination (subset变种)

本文介绍如何通过DFS算法解决给定n个偶数,找到第k个由一半元素组成的组合问题。这些组合按数字顺序和字典序排序。解法涉及递归遍历和计数,适用于n<=20且1<=k<=C(n,n/2)的情况。

1464 · The K-th Combination

Algorithms

Hard

Description

Solution

Notes

Discuss

Leaderboard

Description

There are n individuals whose numbers are 1,2,3,...,nn are even numbers. Selecting half of them have C(n, n/2) combinations. Each combination is sorted by number from small to large, and then the sorted combination is sorted in lexicographic order. Please find the k-th combination.

  • 1 \leq n \leq 20, 1 \leq k \leq C(n, n/2)1≤n≤20,1≤k≤C(n,n/2)

Example

Example 1:


Input:  n=2, k=1  
Output: [1]
Explanation:
All sorted combinations: [1],[2]

Example 2:


Input: n=4, k=2
Output: [1,3]
Explanation:
All sorted combinations: [1,2],[1,3],[1,4],[2,3],[2,4],[3,4]

解法1:DFS。subset的变种。

class Solution {
public:
    /**
     * @param n: The integer n
     * @param k: The integer k
     * @return: Return the combination
     */
    vector<int> getCombination(int n, int k) {
        vector<int> vol;
        helper(n, k, 1, vol);
        return res;
    }
private:
    vector<int> res;
    int cnt = 0;
    void helper(int n, int k, int pos, vector<int> &vol) {        
        if (!res.empty()) return;
        if (vol.size() == (n >> 1)) {    
            cnt++;
            if (cnt == k) {
                res = vol;
            }
            return;
        }
        for (int i = pos; i <= n; i++) {
            vol.push_back(i);
            helper(n, k, i + 1, vol); 
            vol.pop_back();
        }
        return;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值