zoukankan      html  css  js  c++  java
  • [LeetCode] 77. Combinations 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],
    ]

    题意及分析:给出一个n和k,要求求出由n中k个不同的数组成是序列,序列为升序排序。这道题要求所有可能的情况,显然我们可以使用回溯的方法求解,对于每次判断的边界条件为:后面的数要大于前面的数。而且由于这里1到n肯定是递增的,所以继续进行下一层运算的条件可以为 当前位置后面的数。具体看代码实现。

    代码:

    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
    		List<List<Integer>> resList=new ArrayList<>();
    		List<Integer> list=new ArrayList<>();
    		
    		backtracking(resList, list, 1, 1,n, k);
    		return resList; 
        }
    	
    	public void backtracking(List<List<Integer>> resList,List<Integer> list,int t,int start,int n, int k) {
    		if(t>k){
    			resList.add(new ArrayList<>(list));
    		}else{
    			for(int i=start;i<=n;i++){
                    list.add(i);
    				backtracking(resList, list, t+1,i+1, n, k);
    				list.remove(list.size()-1);
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    素数筛的2种方法
    c++含结构体的sort()使用
    构建c++二维vector
    c语言输入单字符避免回车的四种方法
    menset()在c++中的作用
    杭电oj hud1092 1093 活用EOF&n--
    EOF在while(scanf("%d",&n))中的作用
    KMP算法
    图解HTTP(3)
    图解HTTP(2)
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6962789.html
Copyright © 2011-2022 走看看