找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
(所有数字都是正整数,解集不能包含重复的组合。 )
示例1:
输入:
3
7
输出:
[[1,2,4]]
示例2:
输入:
3
9
输出:
[[1,2,6], [1,3,5], [2,3,4]]
import java.util.ArrayList;
import java.util.List;
public class Solution {
int[] a=new int[10];
int K,N;
List<List<Integer>> list=new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum(int k, int n) {
for(int i=1;i<9;i++){
dfs(i,0,0,k,n);
}
return list;
}
public void dfs(int s,int t,int sum,int K,int N) {
if (t <= K && sum <= N) {
if (t == K && sum == N) {
List<Integer> li = new ArrayList<Integer>();
for (int i = 0; i < K; i++) {
li.add(a[i]);
}
list.add(li);
} else if (t <= K && sum + s <=N) {
a[t]=s;
t++;
sum+=s;
for(int j=s+1;j<=10;j++) {
if(sum==N) {
dfs(j, t, sum,K,N);
break;
}else
dfs(j,t,sum,K,N);
}
}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
public class MainClass {
public static String integerArrayListToString(List<Integer> nums, int length) {
if (length == 0) {
return "[]";
}
String result = "";
for(int index = 0; index < length; index++) {
Integer number = nums.get(index);
result += Integer.toString(number) + ", ";
}
return "[" + result.substring(0, result.length() - 2) + "]";
}
public static String integerArrayListToString(List<Integer> nums) {
return integerArrayListToString(nums, nums.size());
}
public static String int2dListToString(List<List<Integer>> nums) {
StringBuilder sb = new StringBuilder("[");
for (List<Integer> list: nums) {
sb.append(integerArrayListToString(list));
sb.append(",");
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int k = Integer.parseInt(line);
line = in.readLine();
int n = Integer.parseInt(line);
List<List<Integer>> ret = new Solution().combinationSum(k, n);
String out = int2dListToString(ret);
System.out.print(out);
}
}
}
/*
leetcode运行时间0秒着实让我尿了,看我好骗
*/