题目:
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.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
给定一个k和n,那么我们找出从1到9为止的所有数中,满足求和个数为k的数,和为n的所有种数。
题解:
此题与之前的combination sum一样。只不过多了一个条件,就是这个k。那么可以用DFS,递归来做,当然也要回溯。只不过结束的条件变为k和n的限制了。其他与combination sum一样。
代码如下:
public class combinationSum3
{
public List<List<Integer>> combinationSum3(int k,int n)
{
int[] nums = new int[10];
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
if(k <= 0 || n <= 0)
return result;
for(int i = 1; i < 10; i++)
nums[i] = i;
DFS(nums,0,n,k,0,list,result,1);
return result;
}
public static void DFS(int[] nums,int count,int n,int k,int sum,ArrayList<Integer> list,List<List<Integer>> result,int start)
{
if(sum == n && count == k)
{
result.add(new ArrayList<Integer>(list));
return;
}
else if(sum > n || count > k)
return;
else if(sum < n && count < k)
{
for(int i = start; i < nums.length; i++)
{
if(sum + nums[i] <= n)
{
if(count + 1 <= k)
{
list.add(nums[i]);
sum += nums[i];
count += 1;
DFS(nums,count,n,k,sum,list,result,i + 1);
list.remove(list.size() - 1);
sum -= nums[i];
count -= 1;
}
}
}
}
}
}
此题可以与之前那几题对比。