LeetCode 0216 Combination Sum III
作者:互联网
1. 题目描述
2. Solution 1
1、思路分析
回溯法。
2、代码实现
package Q0299.Q0216CombinationSumIII;
import java.util.ArrayList;
import java.util.List;
/*
backtracking 回溯
*/
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ans = new ArrayList<>();
combination(ans, new ArrayList<>(), k, 1, n);
return ans;
}
private void combination(List<List<Integer>> ans, List<Integer> curResult, int k, int start, int n) {
if (curResult.size() == k && n == 0) {
ans.add(new ArrayList<>(curResult));
return;
}
for (int i = start; i <= 9; i++) {
curResult.add(i);
combination(ans, curResult, k, i + 1, n - i);
curResult.remove(curResult.size() - 1);
}
}
}
3、复杂度分析
时间复杂度:
标签:int,Sum,List,curResult,ArrayList,ans,new,III,LeetCode 来源: https://www.cnblogs.com/junstat/p/16345877.html