=============stdafx.h=========== #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> // TODO: reference additional headers your program requires here #include <stdlib.h> //use abs true/false #include <iostream> //#include <stdbool.h> //use bool true/false #include <stdlib.h> =============NeighboringNumCombination.cpp=========== #include "stdafx.h" using namespace std; //http://zhidao.baidu.com/question/136069530.html //书架上有21本书,编号从1到21,从其中选4本,其中每两本的编号都不相邻的选法一共有多少种? bool IsHasNeighboringNum(int len, int *xs) //unused { if (1 >= len) { return true; } for (int i = 0; i < (len - 1); i++) { int temp = xs[i]; for (int i2 = (i + 1); i2 < len; i2++) { if (abs(temp - xs[i2]) <= 1) { return false; } } } return true; } bool IsHasNeighboringNumOrdered(int len, int *xs) { if (1 >= len) { return true; } for (int i = 0; i < (len - 1); i++) { if (abs(xs[i] - xs[i + 1]) <= 1) return false; } return true; } inline bool IsOdd(int n) { return (bool) (n & 1); } int count_Combination_NoNeighboring(int n, int r) { if (n <= 0) return 0; switch (r) { case 0: return 0; case 1: return n; } //if (r >= n) return 0; if (IsOdd(n)) { if (r > n / 2 + 1) return 0; if (r == n / 2 + 1) return 1; } else { //is even if (r > n / 2) return 0; if (r == n / 2) return 2; } const int MIN_SAFE_DISTANCE = 2; //enumerate Combination Of NoNeighbor //mark start from #0 to #(n-1) int *aa = (int *)malloc((sizeof (int))*(r + 1)); //holds new memblock readonly *aa = -2; //a trick for speed-up int *a = aa + 1; for (int i = 0; i < r; i++) //init { a[i] = a[i - 1] + MIN_SAFE_DISTANCE; } int count = 0; int iA; //holds smallest index need to re-combination range, if -1 then all combination used do { count += n - a[r - 1]; iA = r - 2; redo: a[iA]++; //new combination starts for (int i = iA + 1; i < r; i++) //iA+1 to r-1 { a[i] = a[i - 1] + MIN_SAFE_DISTANCE; if (a[i] > n) { iA--; //combinaton failed, one number out of range if (iA < 0) //== -1 { goto has_result; } goto redo; } } } while (true); has_result: free(aa); return count; } int _tmain(int argc, _TCHAR* argv[]) { int e = count_Combination_NoNeighboring(21, 4); //n=21, r=4, result 3060 cout << e << '/n'; system("pause"); return 0; }