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],
]
C ode:

[java]  view plain copy
  1. public class Solution {  
  2.     public ArrayList> combine(int n, int k) {  
  3.         ArrayList list = new ArrayList();  
  4.         ArrayList> listsAll = new ArrayList>();  
  5.         allCombine(n, k, 10, list, listsAll);  
  6.         return listsAll;  
  7.           
  8.     }  
  9.       
  10.     public void allCombine(int n, int k, int current, int length, ArrayList list, ArrayList> listsAll) {  
  11.         if (current > n) return;  
  12.         list.add(current);  
  13.         length++;  
  14.         if (list.size() == k) {  
  15.             print(list,listsAll);  
  16.         }  
  17.         allCombine(n, k, current + 1, length, list, listsAll);  
  18.         list.remove(list.size() - 1);  
  19.         allCombine(n, k, current + 1, length, list, listsAll);        
  20.     }  
  21.       
  22.     public void print(ArrayList list, ArrayList> listsAll) {  
  23.         ArrayList temp = new ArrayList(list);  
  24.         listsAll.add(temp);  
  25.     }  
  26. }  

你可能感兴趣的:(leetcode,leetcode)