码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Combinations

时间:2014-09-10 22:24:51      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   log   

//递归结发,计算正确,但是会timeout
1
public class Solution { 2 public List<List<Integer>> combine(int n, int k) { 3 int [] num = new int[n+1]; 4 for (int i=0; i<=n; i++) num[i] = i; 5 List<List<Integer>> result = new ArrayList<List<Integer>>(); 6 7 generateCombine(result, num, 1, k); 8 9 return result; 10 } 11 12 public void generateCombine(List<List<Integer>> result, int [] num, int nowIndex, int k) { 13 if (nowIndex>k) { 14 List<Integer> oneResult = new ArrayList<Integer>(); 15 for (int i=0; i<=k; i++) oneResult.add(num[i]); 16 result.add(oneResult); 17 } else { 18 for (int i=nowIndex; i<num.length; i++) { 19 swap(num, nowIndex, i); 20 generateCombine(result, num, nowIndex+1, k); 21 swap(num, nowIndex, i); 22 } 23 } 24 } 25 26 public void swap(int [] num, int i, int j) { 27 int tmp = num[i]; 28 num[i] = num[j]; 29 num[j] = tmp; 30 } 31 }

 

[LeetCode] Combinations

标签:style   blog   color   io   ar   for   div   sp   log   

原文地址:http://www.cnblogs.com/yuhaos/p/3965182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!