forked from Jyo561/Backtracking
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ksubset.java
53 lines (53 loc) · 963 Bytes
/
ksubset.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Subset{
static void Backtracking(int a[],int k,int n,int input[],int p){
int c[]=new int[n];
int ncan=0;
if(is_a_solution(n,k)){
process_solution(a,n,k,input,p);
}
else{
k++;
ncan=construct_candidate(c,k,n);
for(int i=0;i<ncan;i++) {
a[k-1]=c[i];
Backtracking(a,k,n,input,p);
}
}
}
static int construct_candidate(int c[],int k,int n){
c[0]=0;
c[1]=1;
return 2;
}
static boolean is_a_solution(int k,int n){
if(k-1==(n-1)){
return true;
}
else{
return false;
}
}
static void process_solution(int a[],int n,int k,int input[],int p){
int l=0;
for (int i=0;i<n;i++ ) {
if(a[i]==1){
l++;
}
}
if(l==p){
for (int i=0;i<n;i++ ) {
if(a[i]==1){
System.out.print(input[i]);
}
}
System.out.println();
}
}
public static void main(String[] args) {
int input[]={2,4,3,1,1};
int n=input.length;
int p=3;
int a[]=new int[n];
Backtracking(a,0,n,input,p);
}
}