zoukankan      html  css  js  c++  java
  • leetcode--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],
    ]

    public class Solution {
        /**This code is an implemenatation of bfs idea.<br>
         * @author Averill Zheng
         * @version 2014-06-05
         * @since JDK 1.7
         */ 
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer> > combinations = new ArrayList<List<Integer> >();
    		if(k > 0){
    			for(int i = 0; i < n; ++i){
    				List<Integer> aList = new ArrayList<Integer>();
    				aList.add(i + 1);
    				combinations.add(aList);
    			}
    			if(k > 1){
    				for(int j = 1; j < k; ++j){ //j denotes the number of integer in each list
    					List<List<Integer>> temp = new ArrayList<List<Integer> >();
    					int length = combinations.size();
    					for(int l = 0; l < length; ++l){
    						List<Integer> aList = combinations.get(l);
    						int lastNumber = aList.get(j - 1);
    						if(n - lastNumber >= k - j){ // has enough number to get the k combinations
    							for(int m = lastNumber + 1; m <= n; ++m){
    								List<Integer> newList = new ArrayList<Integer>();
    								newList.addAll(aList);
    								newList.add(m);
    								temp.add(newList);
    							}
    						}
    					}
    					combinations = temp;
    				}
    			}
    		}	
            return combinations;    
        }
    }
    

      

  • 相关阅读:
    vue在new的时候做了什么???
    vue中关于this的指向
    jquery 的本地存储 localStorage
    解读vue实例的双向绑定源码
    node修改数据遇到的坑
    node.js邮箱验证码
    webpack基础配置
    获取时间差。
    js获取时间方法
    node的buffer转换为字符串
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3773977.html
Copyright © 2011-2022 走看看