zoukankan      html  css  js  c++  java
  • lintcode-152-组合

    152-组合

    组给出两个整数n和k,返回从1......n中选出的k个数的组合。

    样例

    例如 n = 4 且 k = 2
    返回的解为:
    [[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

    标签

    回溯法 数组

    思路

    使用回溯和递归

    code

    class Solution {
    public:
        /**
         * @param n: Given the range of numbers
         * @param k: Given the numbers of combinations
         * @return: All the combinations of k numbers out of 1..n
         */
        vector<vector<int> > combine(int n, int k) {
            // write your code here
            if (n <= 0 || k <= 0) {
                return vector<vector<int> >();
            }
    
            vector<vector<int> > result;
            vector<int> temp;
            isInsert(result, temp, 1, n, k);
            return result;
        }
    
        void isInsert(vector<vector<int> > &result, vector<int> &temp, int current, int n, int k) {
            if (temp.size() == k) {
                result.push_back(temp);
                return;
            }
            if (current <= n) {
                temp.push_back(current);
                isInsert(result, temp, current+1, n, k);
                temp.pop_back();
                isInsert(result, temp, current + 1, n, k);
            }
        }
    };
    
  • 相关阅读:
    在centos上搭建Git服务器
    glog日志库移植Android平台
    水葱
    路易斯安娜鸢尾
    再力花
    矮生百慕大
    洒金珊瑚
    八角金盘
    锦绣杜鹃
    茶梅球
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7259564.html
Copyright © 2011-2022 走看看