题目:
解答:
1 class Solution { 2 int f(int n, int m) 3 { 4 if (n == 1) 5 { 6 return 0; 7 } 8 int x = f(n - 1, m); 9 return (m + x) % n; 10 } 11 public: 12 int lastRemaining(int n, int m) 13 { 14 return f(n, m); 15 } 16 17 };
方法二:数学+迭代
class Solution { public: int lastRemaining(int n, int m) { int f = 0; for (int i = 2; i != n + 1; ++i) f = (m + f) % i; return f; } };