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);
            		}
            	}   
            }
        }
    }
    

      

  • 相关阅读:
    ES6、ES7、ES8特性
    【react】XXX项目环境搭建
    map
    vector
    list
    米勒素数模板
    POJ-2421-Constructing Roads(最小生成树 普利姆)
    HDU1301 Jungle Roads(Kruskal)
    Truck History(prime)
    phpstorm快捷键和激活
  • 原文地址:https://www.cnblogs.com/lautsie/p/3239357.html
Copyright © 2011-2022 走看看