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

    题目:

    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],
    ]
    

     题解:

     这道题就是用DFS(参考Work BreakII)的循环递归处理子问题的方法解决。n为循环的次数,k为每次尝试的不同数字。用到了回溯。

     代码如下:

     1     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
     2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
     3         if(n <= 0||n < k)
     4             return res;
     5         ArrayList<Integer> item = new ArrayList<Integer>();    
     6         dfs(n,k,1,item, res);//because it need to begin from 1
     7         return res;
     8     }
     9     private void dfs(int n, int k, int start, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> res){
    10         if(item.size()==k){
    11             res.add(new ArrayList<Integer>(item));//because item is ArrayList<T> so it will not disappear from stack to stack
    12             return;
    13         }
    14         for(int i=start;i<=n;i++){
    15             item.add(i);
    16             dfs(n,k,i+1,item,res);
    17             item.remove(item.size()-1);
    18         }
    19     }

    Reference:http://blog.csdn.net/linhuanmars/article/details/21260217

  • 相关阅读:
    Welcome to my website
    花生壳
    Gentle.NET Attribute
    发布WebFtp 控件(ASP.NET控件,用以web方式进行文件上下传操作)
    发布数据库连接字符串生成工具
    发布语法加亮控件(SyntaxTextBox)
    .NET中现有的 ORM 工具(转)
    发布Oracle存储过程包c#代码生成工具(CodeRobot)
    ASCII码表
    爱上语法高亮控件ICSharpCode.TextEditor ~o~
  • 原文地址:https://www.cnblogs.com/springfor/p/3877168.html
Copyright © 2011-2022 走看看