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 }
  • 相关阅读:
    Word Search
    Subsets
    Combinations
    Search a 2D Matrix
    求比正整数N大的最小正整数M,且M与N的二进制表示中有相同数目的1
    Set Matrix Zeroes
    Unity学习笔记—— 常用脚本函数
    学习 各个数据结构
    unity调用 安卓相册
    设置 相机跟随 主角及视角 滑动
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4341920.html
Copyright © 2011-2022 走看看