# LeetCode Combination Sum III

213人阅读 评论(0)

Description:

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.

Solution:

1.递归到10

2.当前的ArrayList中包含的数字正好有k个

import java.util.*;

public class Solution {
int n, k;
List<List<Integer>> list = new ArrayList<List<Integer>>();

public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
this.n = n;

dfs(1, 0, new ArrayList<Integer>());
return list;
}

void dfs(int num, int tempSum, ArrayList<Integer> array) {
if (num == 10) {
if (tempSum == n && array.size() == k)
return;
}

dfs(num + 1, tempSum, array);
if (tempSum + num <= n) {
dfs(num + 1, tempSum + num, array);
array.remove(array.size() - 1);
}
}
}

import java.util.*;

public class Solution {
int n, k;
List<List<Integer>> list = new ArrayList<List<Integer>>();

public List<List<Integer>> combinationSum3(int k, int n) {
this.k = k;
this.n = n;

dfs(1, 0, 0, new ArrayList<Integer>());
return list;
}

void dfs(int num, int selectedNum, int tempSum, ArrayList<Integer> array) {
if (selectedNum == k) {
if (tempSum == n)
return;
}

for (int i = num; i <= 10 - (k - selectedNum); i++)
if (tempSum + i <= n) {
dfs(i + 1, selectedNum + 1, tempSum + i, array);
array.remove(array.size() - 1);
}

}

}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：61826次
• 积分：3254
• 等级：
• 排名：第10432名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论