iQOO 與京東達成戰略合作:目標三年手機銷量累計超 2200 萬臺,銷售額破 500 億元
阿新 • • 發佈:2021-12-14
描述
給定兩個整數n
和k
,返回範圍[1, n]
中所有可能的k
個數的組合。
你可以按任何順序返回答案。
連結
77. 組合 - 力扣(LeetCode) (leetcode-cn.com)
題解
1 class Solution { 2 List<List<Integer>> res = new ArrayList<>(); 3 Deque<Integer> path = new ArrayDeque<>(); 4 public List<List<Integer>> combine(intn, int k) { 5 if( n <= 0 || k<= 0) { 6 return res; 7 } 8 combineHelper(n, k, 1); // 遞迴的時候從一 開始 9 return res; 10 } 11 12 public void combineHelper(int n, int k, int StartIndex) { 13 if(path.size() == k) { // 14 res.add(newArrayList<>(path)); 15 return; 16 } 17 18 for(int i = StartIndex; i <= n - (k-path.size()) +1; i++) { // 剪枝 19 path.addLast(i); 20 combineHelper(n, k, i + 1); 21 path.removeLast(); 22 } 23 } 24 }
參考
carl