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

    组合DFS。对其中需要无重复,非降序的要求,只需做个小小的“剪枝”判断就行了。

    import java.util.ArrayList;
    import java.util.Collections;
     
    public class Solution {
        public ArrayList<ArrayList<Integer>> combine(int n, int k) {
            // Start typing your Java solution below
            // DO NOT write main() function
            ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
            int[] combination = new int[k];
            dfs(combination, 0, k, n, ans);       
            return ans;
        }
         
        public void dfs(int[] combination, int d, int k, int n, ArrayList<ArrayList<Integer>> arr) {
            if (d == k) {
                ArrayList<Integer> a = new ArrayList<Integer>();
                for (int i = 0; i < k; i++) {
                        a.add(combination[i]);
                }
                Collections.sort(a);
                arr.add(a);
                return;
            }
            else {
            	for (int i = 0; i < n; i++) {
            		if (d == 0 || i+1 > combination[d-1]) {
    	        		combination[d] = i+1;
    	        		dfs(combination, d+1, k, n, arr);
            		}
            	}   
            }
        }
    }
    

      

  • 相关阅读:
    052-14
    052-13
    css垂直居中
    js中的null 和undefined
    给数组添加属性
    js中避免函数名和变量名跟别人冲突
    js变量问题
    Life
    BFC和haslayout
    json文件
  • 原文地址:https://www.cnblogs.com/lautsie/p/3239357.html
Copyright © 2011-2022 走看看