// Recursive trigger, correct calculation, but timeout
1 public class solution {2 public 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 <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