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

题解:

和N-Queens都是NP问题,利用helper迭代,迭代的stop condition是item.size() == k, 此时把item的copy加到res中。

若item.size()还没有到k, item加i, 然后继续迭代,到了k返回后去掉item最后一个值。

这里的start是递归的关键,每次recursion时, 加完i后,把i+1赋给start继续recursion.

AC Java:

 1 public 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 || n<k){
 5             return res;
 6         }
 7         helper(n,k,1,new ArrayList<Integer>(), res);
 8         return res;
 9     }
10     private void helper(int n, int k, int start, List<Integer> item, List<List<Integer>> res){
11         if(item.size() == k){
12             res.add(new ArrayList<Integer>(item));
13             return;
14         }
15         for(int i = start; i<=n; i++){
16             item.add(i);
17             helper(n,k,i+1,item,res);
18             item.remove(item.size()-1);
19         }
20     }
21 }

 跟上Combination Sum, Combination Sum II, Combination Sum III, Factor Combinations

你可能感兴趣的:(LeetCode Combinations)