Home >Backend Development >C#.Net Tutorial >Find the combination of any m numbers in a number of length n

Find the combination of any m numbers in a number of length n

巴扎黑
巴扎黑Original
2016-12-20 14:15:251605browse

The problem can be decomposed into:
1. First select the number with the largest number from n numbers, then select m-1 numbers from the remaining n-1 numbers, until n-(m-1) numbers are selected until 1 number is selected.
2. Select the next smallest number from n numbers and continue step 1 until the current number with the largest optional number is m.
Obviously, the above method is a recursive process, which means that all combinations can be obtained very cleanly using the recursive method.

Code:

package algorithm.ms100;
public class CtzHe {
private int[] array = {1,2,3,4,5};
private int[] b= new int[3];
private int M = 3;
public void combine( int a[], int n, int m)
{ 
for(int i=n; i>=m; i--)   // 注意这里的循环范围
{
 b[m-1] = i - 1;
 if (m > 1)
 combine(a,i-1,m-1);
 else                     // m == 1, 输出一个组合
 {   
 for(int j=M-1; j>=0; j--)
 System.out.print( a[b[j]] + " ");
 System.out.println();
 }
}
}
public static void main(String[] args) {
CtzHe c = new CtzHe();
c.combine(c.array, 5, 3);
}
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn