简单题,溜溜手。
C:
#include <stdlib.h> #include <string.h> void allocation(int *givenArr, int currentCandie, int currentPeople, int candies, int num_people) { if (candies <= 0) return; givenArr[currentPeople] += currentCandie < candies ? currentCandie : candies; int nextPeople = currentPeople == num_people - 1 ? 0 : currentPeople + 1; allocation(givenArr, currentCandie + 1, nextPeople, candies - currentCandie, num_people); } int *distributeCandies(int candies, int num_people, int *returnSize) { int *reArr = (int *)malloc(sizeof(int) * num_people); memset(reArr, 0, sizeof(int) * num_people); *returnSize = num_people; allocation(reArr, 1, 0, candies, num_people); return reArr; }
JAVA:
public int[] distributeCandies(int candies, int num_people) { int[] reArr = new int[num_people]; allocation(reArr, 0, 1, candies); return reArr; } private final void allocation(int[] alloc, int currentPeople, int currentCandie, int candies) { if (candies <= 0) return; alloc[currentPeople] += currentCandie < candies ? currentCandie : candies; int nextPeople = currentPeople == alloc.length - 1 ? 0 : currentPeople + 1; allocation(alloc, nextPeople, currentCandie + 1, candies - currentCandie); }
JS:
/** * @param {number} candies * @param {number} num_people * @return {number[]} */ var distributeCandies = function (candies, num_people) { let reArr = new Array(num_people); reArr.fill(0); allocation(reArr, 0, 1, candies); return reArr; }; var allocation = function (arr, currentPeople, currentCandie, candies) { if (candies <= 0) return; arr[currentPeople] += currentCandie < candies ? currentCandie : candies; let nextPeople = currentPeople == arr.length - 1 ? 0 : currentPeople + 1; allocation(arr, nextPeople, currentCandie + 1, candies - currentCandie); }