LeetCode Combination Sum III

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:

这种DFS有两种写法,这里进行总结。

写法一:

每层的递归是根据当前这个数字是否添加进行。所以最后终止条件有两个

1.递归到10

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

复杂度为2^10


写法二:

每层的递归是根据第i个选取的数字是多少。递归地终止条件只要一个,就是加入ArrayList的数字有k个。

复杂度为2^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)
				list.add(new ArrayList<Integer>(array));
			return;
		}

		dfs(num + 1, tempSum, array);
		if (tempSum + num <= n) {
			array.add(num);
			dfs(num + 1, tempSum + num, array);
			array.remove(array.size() - 1);
		}
	}
}
写法二代码:

很明显写法二比较适合这道题目,需要注意的就是每一层,选取第selectedNum+1个元素的时候,元素的范围不是无限制的,需要小于等于 10 - ( k - selectedNum);如果直接是小于10也可以,那就需要递归的时候判断一下,num<10的条件是否成立,否则num会等于10

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)
				list.add(new ArrayList<Integer>(array));
			return;
		}

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

	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值