zoukankan      html  css  js  c++  java
  • leetcode 77 组合 给定数n和k,返回1.。n内所有K个数的组合

     1 class Solution {
     2 public:                 //递归  第一个位置分别为从1-n,对于每个值,后面的k-1个数再从后面的数里选剩下的k-1个数(子递归),等到第一个位置取到n-k的时候,剩下的k-1个正好是一种答案。
     3     vector<vector<int>> combine(int n, int k) {
     4         if(k==0 || n==0)
     5         {
     6             return {};
     7         }
     8         vector<int> temp(k,0);//初始化记得不然下标访问不到
     9         vector<vector<int>> res;
    10         int count=0;
    11         int start=1;
    12         DFS(res,temp,count,start,n,k);
    13         return res;
    14     }
    15     void DFS(vector<vector<int>>& res,vector<int>& temp,int& count,int start,int end,int k)
    16     {
    17         if(count==k)
    18         {
    19             res.push_back(temp);
    20             return;
    21         }
    22         for(int i=start;i<=end;i++)
    23         {
    24             temp[count++]=i;
    25             DFS(res,temp,count,i+1,end,k);
    26             count--;
    27         }
    28     }
    29 };
    每天进步一点点~
  • 相关阅读:
    多态
    java8的十大新特性
    Floyd最短路径算法
    ES6(六)函数扩展
    ES6(五)数组扩展
    ES6(四)数值扩展
    ES6(一)解构赋值
    store封装
    ipad方案
    pyinstaller编译打包为pyd
  • 原文地址:https://www.cnblogs.com/libin123/p/14660094.html
Copyright © 2011-2022 走看看