zoukankan      html  css  js  c++  java
  • leetcode------Combinations

    标题:

    Combinations

    通过率: 30.5%
    难度: 中等

    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-k+1,所以从1开始然后进入迭代,放够k个元素后进行add

    具体看代码:

     1 public class Solution {
     2     private ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>();
     3     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
     4         for (int i=1; i<=n-k+1; ++i){
     5             ArrayList<Integer> list = new ArrayList<Integer>();
     6             list.add(i);
     7             cal(list, i+1, n, k-1); 
     8         }
     9         return arrays;
    10     }
    11     public void cal(ArrayList<Integer> list, int start, int end, int k){
    12         if (k == 0){
    13             ArrayList<Integer> result = new ArrayList<Integer>(list);
    14             arrays.add(result);
    15         }
    16         for (int i=start; i<=end; ++i){
    17             list.add(i);
    18             cal(list, i+1, end, k-1);
    19             list.remove(list.size()-1);
    20         }
    21     }
    22 }
  • 相关阅读:
    C++中substr函数的用法
    最小生成树-克鲁斯卡尔模板
    最小生成树-prim算法模板
    1064. 朋友数(20)
    1076. Wifi密码 (15)【模拟】
    二分搜索与二分答案
    HDU 1969 Pie【二分】
    1047. 编程团体赛(20)
    1057. 数零壹(20)
    L2-3. 悄悄关注【STL+结构体排序】
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4341920.html
Copyright © 2011-2022 走看看