一、题目描述
- 给定一个不重复数组char[] ch,从数组中取出num 个元素,将num个元素组合起来,求有多少种组合
- 例如:
数组 char[] ch:{"a", "b", "c"};
元素num :取出3个元素
结果:10种
[a, a, b]
[b, b, c]
[a, a, a]
[c, c, c]
[a, b, c]
[a, a, c]
[a, b, b]
[b, b, b]
[a, c, c]
[b, c, c]
思路一: (思想,使用了就不再使用)
111,112,113,114
122,123,124
133,134
144
222,223,224
233,234
244
333,334
344
444
思路二: (思想, 3个a有多少种, 2个a有多少种, 1个a有多少种组合)
aaa 1
aab,aac,aad 3
abb, abc,abd, acc,acd, add 6
bbb, bbc,bbd, bcd,bcc,bdd, ccc,ccd,cdd,ddd 10
二、解决
方案一(不推荐)
public static void main(String[] args) {
String[] combineSource = {"a", "b", "c"};
HashSet<String> combineRes = new HashSet<>();
combine(combineSource, combineRes, 3L);
for (String com: combineRes){
System.out.println(com);
}
System.out.printf(combineRes.size() + "");
}
public static void combine(String[] combineSource, Set<String> combineRes, Long remainTotalNum) {
combine(combineSource, combineRes, "", remainTotalNum);
}
public static void combine(String[] combineSource, Set<String> combineRes, String combineStr, Long remainTotalNum) {
String prxStr = combineStr;
for (String str: combineSource) {
combineStr = prxStr + str;
if (combineStr.length() == remainTotalNum) {
char[] chars = combineStr.toCharArray();
Arrays.sort(chars);
combineRes.add(Arrays.toString(chars));
continue;
}
combine(combineSource, combineRes, combineStr, remainTotalNum);
}
}
方案二
class Solution {
List<List<Integer>> lists =new ArrayList<>();
List<Integer> list=new ArrayList<>();
int num=0;
public List<List<Integer>> combine(int n, int k) {
int[] a=new int[n];
num=k;
for(int i=0;i<n;i++){
a[i]=i+1;
}
dfs(a,0);
return lists;
}
public void dfs(int[] a,int i){
if(list.size() == num){
lists.add(new ArrayList<>(list));
return;
}
if(i == a.length){
return;
}
list.add(a[i]);
dfs(a,i+1);
//dfs(a,i);//请注意,如果要求组合方式中有可以重复的元素,此处不加1
list.remove(list.size()-1);
dfs(a,i+1);
}
/**
* 从 n个元素中获取k个元素; 其中n表示 1到n 的数字: 例如n=10 则表示1到10的数字
* @param args
*/
public static void main(String[] args) {
Solution solution = new Solution();
List<List<Integer>> combine = solution.combine(2, 2);
System.out.printf("");
}
}