LeetCode Combination Sum III

本文探讨了如何找出从1到9中满足特定数量且总和等于给定数值的所有组合。通过递归深度优先搜索(DFS)算法实现,提供了解决方案的详细步骤和源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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;
					}
				}
			}
		}
	}
}

此题可以与之前那几题对比。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值