LeetCode 77. Combinations

原題連接在這裏:https://leetcode.com/problems/combinations/html

題目:post

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.url

For example,
If n = 4 and k = 2, a solution is:spa

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

題解:code

backtracking, dfs迭代的stop condition是item.size() == k, 此時把item的copy加到res中.htm

Time Complexity: exponential.blog

Space:O(k). stack space.leetcode

AC Java:rem

 1 class Solution {
 2     public List<List<Integer>> combine(int n, int k) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(n<=0 || k<=0 || k>n){
 5             return res;
 6         } 
 7         dfs(n, k, 1, new ArrayList<Integer>(), res);
 8         return res;
 9     }
10     
11     private void dfs(int n, int k, int start, List<Integer> item, List<List<Integer>> res){
12         if(item.size() == k){
13             res.add(new ArrayList<Integer>(item));
14             return;
15         }
16         for(int i = start; i<=n; i++){
17             item.add(i);
18             dfs(n, k, i+1, item, res);
19             item.remove(item.size()-1);
20         }
21     }
22 }

 相似Combination SumCombination Sum IICombination Sum IIIFactor CombinationsSubsetsPermutationsN-Queensget

相關文章
相關標籤/搜索