首页 > 其他 > 详细

LeetCode Combinations

时间:2015-09-27 11:07:29      阅读:138      评论:0      收藏:0      [点我收藏+]

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

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

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

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 }

 

LeetCode Combinations

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4841951.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!