java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846 |
---|
文章目录

- 此题是77题的扩展题,仅仅加了一个条件而已,就是找到的k个数,必须等于n。
- 而77题,仅仅是找到k个数即可,不需要等于n
🏆LeetCode77. 组合https://blog.csdn.net/grd_java/article/details/136539120 |
---|
- 77题本身的枝剪操作依然需要
- 如果当前组合的值已经>n了,说明没有递归的必要了,因为怎么都不可能==n了。可以进行枝剪操作

class Solution {int k,n;public List<List<Integer>> combinationSum3(int k, int n) {this.k = k;this.n = n;List<List<Integer>> lists = new ArrayList<List<Integer>>();Integer[] records = new Integer[k];backTracking(lists,records,0,1,0);return lists;}public void backTracking(List<List<Integer>> lists, Integer[] records,int row,int column,int sum){if(column>9 || sum>n) return;else if(records.length + 9 - column + 1 < k) return;else{records[row] = column;int curSum = sum+column;if( curSum > n) return;if(row == k-1){if(curSum == n)lists.add(List.of(records));}else{backTracking(lists,records,row+1,column+1,curSum);}backTracking(lists,records,row,column+1,sum);}}
}