zoukankan      html  css  js  c++  java
  • Combinations

    Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

    For example,
    If n = 4 and k = 2, a solution is:

    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]
    思路:本题就是一个组合问题,举个例子就会明白了。例如n=4,k=2,则先将1放入一数组中,然后step记为1,然后循环遍历2加入数组,step记为2,依次加入,等step==k时停止,最后将这个数组加入到vector<vector<int> >中。如果没到达4,则pop最后一个元素,在往后push元素。直到4位置。等到以1开头的组合遍历结束,则对2进行上述操作。递归进行。
    class Solution {
    public:
        void search_combine(vector<vector<int> > &result,vector<int> &data,int n,int k,int index,int step)
        {
            if(step==k)
            {
                result.push_back(data);
                return;
            }
            for(int i=index+1;i<=n;i++)
            {
                data.push_back(i);
                search_combine(result,data,n,k,i,step+1);
                data.pop_back();
            }
        }
        vector<vector<int> > combine(int n, int k) {
            vector<vector<int> > result;
            vector<int> data;
            search_combine(result,data,n,k,0,0);
            return result;
        }
    };
    
    
    
     
  • 相关阅读:
    ALV 填值返回更新屏幕
    alv 的几种形式 和 函数
    JS 截取字符串的空格
    codeigniter 轻量级架构知识初习
    之前的博客挂掉了
    在服务器上运行php文件来执行操作
    浏览器判断
    php 汉字判断
    web 套打方法实现打印机功能
    WIN8
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3640960.html
Copyright © 2011-2022 走看看