[LeetCode]Combinations

LeetCode: https://oj.leetcode.com/problems/combinations/

該題採用DFS的方法來解決,和Permutations,N-Queens的解決方式類似:

代碼如下:

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



發佈了65 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章