日期:2014-05-16 浏览次数:20383 次
题目源自: Linux C编程一站式学习的习题
欢迎拍砖~
c版
#include <stdio.h> #define N 5 #define M 5 #define IS_COMBINATION 1 int arr[N]; void printArr(void){ int j = M,i ; if(IS_COMBINATION){ for(i=0;i<M-1;i++){ if(arr[i]>arr[i+1])return; } } for(i=0;i<j;i++){ printf("%d ",arr[i]); } printf("\n"); } void swap(int i , int j){ int temp = arr[i];arr[i]=arr[j];arr[j]=temp; } void permutation(int k){ int i = N-k; if(k==N-M){ printArr(); return; } for(;i<N;i++){ swap(N-k,i); permutation(k-1); swap(N-k,i); } } int main(void){ int i = 0 ; for(;i<N;i++ ){arr[i]=i+1;} permutation(N ); return 0; }?
?
java版
static int N = 5,M=3; static boolean IS_COMBINATION = false; static int[] arr = new int[N]; static void print(){ if(IS_COMBINATION){ for(int i=0;i<M-1; i++){ if(arr[i]>arr[i+1]){ return; } } } System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, M))); } static void swap(int i , int j){ arr[i]=arr[j]+0*(arr[j]=arr[i]); } static void permutation(int k){ if(k==N-M){ print(); return; } for (int i = N-k; i < N; i++) { swap(i, N-k); permutation(k-1); swap(i, N-k); } } public static void main(String[] args) { for (int i = 0; i < N; i++) { arr[i]=i+1; } permutation(N); }?
?
javascript版
var N = 5,M = 1 , IS_COMBINATION = true ; var arr = [] ; for(var i = 0 ; i<N ;i++){ arr[i]=i+1; } var print = function(){ if(IS_COMBINATION){ for(var i=0;i<M-1; i++){ if(arr[i]>arr[i+1]){ console.log(arr); return; } } } console.log(arr.slice(0,M)); } var swap = function(i,j){ arr[i]=arr[j]+0*(arr[j]=arr[i]); } var permutation = function(k){ if(k==N-M){ print(); return; } for(var i = N-k ; i< N ; i++){ swap(N-k,i); permutation(k-1); swap(N-k,i); } } permutation(N);?
?