LeetCode 77. Combinations

原题链接在这里:https://leetcode.com/problems/combinations/

题目:

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],
]

题解:

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

Time Complexity: exponential.

Space:O(k). stack space.

AC Java:

 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 }

AC Python:

 1 class Solution:
 2     def combine(self, n: int, k: int) -> List[List[int]]:
 3         res = []
 4         self.dfs(n, k, 1, [], res)
 5         return res
 6     
 7     def dfs(self, n: int, k: int, start: int, item: List[int], res: List[List[int]]) -> None:
 8         if len(item) == k:
 9             res.append(item[:])
10             return
11         
12         for i in range(start, n + 1):
13             item.append(i)
14             self.dfs(n, k, i + 1, item, res)
15             item.pop()
16         

类似Combination SumCombination Sum IICombination Sum IIIFactor CombinationsSubsetsPermutationsN-Queens

posted @ 2015-09-27 10:40  Dylan_Java_NYC  阅读(610)  评论(0编辑  收藏  举报